package router

import (
	"metazone.cc/metalab/internal/config"
	"metazone.cc/metalab/internal/middleware"
	"metazone.cc/metalab/internal/model"

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

// setupAdminRoutes 注册管理后台页面和 API 路由
func setupAdminRoutes(r *gin.Engine, cfg *config.Config, d *dependencies) {
	// --- 管理后台 SSR 页面 ---
	adminPages := r.Group("/admin")
	adminPages.Use(d.authMdw.AdminAuth())
	adminPages.Use(middleware.RequirePageRole(model.RoleModerator))
	adminPages.Use(middleware.CSRF(cfg))
	adminPages.Use(func(c *gin.Context) {
		middleware.SetCSRFToken(c, cfg)
		c.Next()
	})
	{
		adminPages.GET("/", d.adminCtrl.Dashboard)
		adminPages.GET("/users", d.adminCtrl.UsersPage,
			middleware.RequirePageRole(model.RoleAdmin))
		adminPages.GET("/audits", d.auditCtrl.AuditPage,
			middleware.RequirePageRole(model.RoleAdmin))
		adminPages.GET("/posts", d.adminPostCtrl.PostsPage)
		adminPages.GET("/site-settings", d.siteSettingCtrl.SiteSettingsPage,
			middleware.RequirePageRole(model.RoleOwner))
	}

	// --- 管理后台 API ---
	adminAPI := r.Group("/api/admin")
	adminAPI.Use(d.authMdw.Required())
	adminAPI.Use(middleware.RequireMinRole(model.RoleAdmin))
	adminAPI.Use(middleware.CSRF(cfg))
	{
		adminAPI.GET("/users", d.adminCtrl.ListUsers)
		adminAPI.PUT("/users/:uid/status", d.adminCtrl.UpdateUserStatus)
		adminAPI.POST("/users/:uid/reset-token", d.adminCtrl.ResetToken)
		adminAPI.GET("/audits", d.auditCtrl.ListAudits)
		adminAPI.POST("/audits/:id/approve", d.auditCtrl.Approve)
		adminAPI.POST("/audits/:id/reject", d.auditCtrl.Reject)
	}

	// --- 站点设置 API（仅 owner） ---
	siteSettingsAPI := r.Group("/api/admin/site-settings")
	siteSettingsAPI.Use(d.authMdw.Required())
	siteSettingsAPI.Use(middleware.RequireMinRole(model.RoleOwner))
	siteSettingsAPI.Use(middleware.CSRF(cfg))
	{
		siteSettingsAPI.GET("", d.siteSettingCtrl.GetSettings)
		siteSettingsAPI.PUT("", d.siteSettingCtrl.UpdateSetting)
		siteSettingsAPI.PUT("/bool", d.siteSettingCtrl.UpdateBoolSetting)
		siteSettingsAPI.GET("/bool", d.siteSettingCtrl.GetBoolSetting)
	}

	// --- 帖子管理 API（admin+） ---
	adminPostAPI := r.Group("/api/admin/posts")
	adminPostAPI.Use(d.authMdw.Required())
	adminPostAPI.Use(middleware.RequireMinRole(model.RoleAdmin))
	adminPostAPI.Use(middleware.CSRF(cfg))
	{
		adminPostAPI.POST("/:id/approve", d.adminPostCtrl.Approve)
		adminPostAPI.POST("/:id/reject", d.adminPostCtrl.Reject)
		adminPostAPI.POST("/:id/lock", d.adminPostCtrl.Lock)
		adminPostAPI.POST("/:id/unlock", d.adminPostCtrl.Unlock)
		adminPostAPI.POST("/:id/restore", d.adminPostCtrl.Restore)
	}
}
