package routes

import (
	"stock-user-system/internal/config"
	"stock-user-system/internal/handlers"
	"stock-user-system/internal/middleware"
	"stock-user-system/internal/models"

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

func Setup(cfg *config.Config, db *gorm.DB) *gin.Engine {
	authHandler := &handlers.AuthHandler{DB: db, CFG: cfg}
	adminHandler := &handlers.AdminHandler{DB: db, CFG: cfg}

	r := gin.Default()

	// CORS
	r.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization")
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})

	r.Use(middleware.AuthMiddleware(cfg, db))

	// 公开接口（仅登录）
	r.POST("/api/auth/login", authHandler.Login)

	// 受保护接口
	auth := r.Group("/api/auth")
	auth.Use(middleware.RequireAuth())
	{
		auth.GET("/me", authHandler.Me)
		auth.POST("/logout", authHandler.Logout)
	}

	// 管理员接口
	admin := r.Group("/api/admin")
	admin.Use(middleware.RequireAuth(), middleware.RequireRoles(models.RoleAdmin, models.RoleSystemAdmin))
	{
		admin.GET("/users", adminHandler.ListUsers)
		admin.POST("/users", adminHandler.CreateUser)
		admin.PUT("/users/:id", adminHandler.UpdateUser)
		admin.DELETE("/users/:id", adminHandler.DeleteUser)
		admin.GET("/roles", adminHandler.ListRoles)
	}

	return r
}
