package router

import (
	"material_texture/internal/config"
	"material_texture/internal/handlers"
	"material_texture/internal/middleware"
	"material_texture/internal/repository"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Setup(db *gorm.DB, cfg *config.Config) *gin.Engine {
	r := gin.Default()

	// 健康检查（无需认证）
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	// 初始化仓库
	materialRepo := repository.NewMaterialRepository(db)
	bindingRepo := repository.NewBindingRepository(db)

	// 初始化处理器
	materialHandler := handlers.NewMaterialHandler(materialRepo)
	bindingHandler := handlers.NewBindingHandler(bindingRepo, materialRepo)

	// API v1 路由组
	v1 := r.Group("/api/v1")
	v1.Use(middleware.TokenAuth(cfg.APIToken))
	{
		// 材质 CRUD
		materials := v1.Group("/materials")
		{
			materials.GET("", materialHandler.List)
			materials.POST("", materialHandler.Create)
			materials.GET("/:id", materialHandler.GetByID)
			materials.PUT("/:id", materialHandler.Update)
			materials.DELETE("/:id", materialHandler.Delete)

			// 绑定管理
			materials.POST("/:id/bindings", bindingHandler.BindMaterial)
			materials.DELETE("/:id/bindings", bindingHandler.UnbindMaterial)
			materials.GET("/:id/groups", bindingHandler.GetGroupsByMaterial)
		}

		// 根据group_id查询材质
		v1.POST("/groups/materials", bindingHandler.GetMaterialsByGroups)
	}

	return r
}
