package main

import (
	"log"

	"material_texture/internal/config"
	"material_texture/internal/models"
	"material_texture/internal/router"
)

func main() {
	// 加载配置
	cfg := config.Load()

	// 连接数据库
	db := config.NewDatabase(cfg)

	// 自动迁移表结构
	if err := db.AutoMigrate(&models.Material{}, &models.MaterialBinding{}); err != nil {
		log.Fatalf("Failed to migrate database: %v", err)
	}

	// 添加唯一约束（GORM的uniqueIndex在某些情况下可能不生效）
	db.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_unique_material_group
		ON material_bindings(material_id, group_id)`)

	log.Println("Database migrated successfully")

	// 设置路由
	r := router.Setup(db, cfg)

	// 启动服务器
	log.Printf("Server starting on port %s", cfg.ServerPort)
	if err := r.Run(":" + cfg.ServerPort); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
