package router

import (
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"

	"mengyaping-backend/handlers"
	"mengyaping-backend/middleware"
)

// SetupRouter 设置路由
func SetupRouter() *gin.Engine {
	r := gin.Default()

	// CORS配置
	r.Use(cors.New(cors.Config{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Admin-Token"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// 创建处理器
	websiteHandler := handlers.NewWebsiteHandler()
	settingsHandler := handlers.NewSettingsHandler()

	// API路由组
	api := r.Group("/api")
	{
		// 健康检查
		api.GET("/health", func(c *gin.Context) {
			c.JSON(200, gin.H{
				"status":  "ok",
				"message": "服务运行正常",
			})
		})

		// 公开：监控调度信息（仅展示）
		api.GET("/monitor/settings", settingsHandler.GetPublicMonitorSettings)

		// 网站 / 分组 — 读操作公开
		api.GET("/websites", websiteHandler.GetWebsites)
		api.GET("/websites/:id", websiteHandler.GetWebsite)
		api.GET("/groups", websiteHandler.GetGroups)
		api.GET("/groups/:id", websiteHandler.GetGroup)

		// 管理：写操作需 ADMIN_TOKEN
		admin := api.Group("")
		admin.Use(middleware.AdminAuth())
		{
			admin.POST("/websites", websiteHandler.CreateWebsite)
			admin.PUT("/websites/:id", websiteHandler.UpdateWebsite)
			admin.DELETE("/websites/:id", websiteHandler.DeleteWebsite)
			admin.POST("/websites/:id/check", websiteHandler.CheckWebsiteNow)
			admin.POST("/groups", websiteHandler.AddGroup)
			admin.PUT("/groups/:id", websiteHandler.UpdateGroup)
			admin.DELETE("/groups/:id", websiteHandler.DeleteGroup)

			admin.GET("/admin/config", settingsHandler.GetAdminConfig)
			admin.PUT("/admin/config", settingsHandler.PutAdminMonitorConfig)
		}
	}

	return r
}
