package controller

import (
	"html/template"
	"net/http"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/config"
	"metazone.cc/metalab/internal/session"
	"metazone.cc/metalab/internal/theme"

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

// AuthController 认证相关页面 + API
type AuthController struct {
	authService    authUseCase
	sessionManager *session.Manager
	rateLimiter    rateLimiter
	cfg            *config.Config
	siteSettings   *config.SiteSettings
}

// NewAuthController 构造函数
func NewAuthController(authService authUseCase, sm *session.Manager, limiter rateLimiter, cfg *config.Config, siteSettings *config.SiteSettings) *AuthController {
	return &AuthController{authService: authService, sessionManager: sm, rateLimiter: limiter, cfg: cfg, siteSettings: siteSettings}
}

// RegisterPage 注册页面（已登录用户重定向到首页）
func (ac *AuthController) RegisterPage(c *gin.Context) {
	if _, exists := c.Get("uid"); exists {
		c.Redirect(http.StatusFound, "/")
		return
	}
	// 优先从 DB 读取社区准则，为空时 fallback 到静态文件
	guidelinesHTML := ac.siteSettings.Get("site.guidelines", "")
	var guidelines template.HTML
	if guidelinesHTML != "" {
		guidelines = template.HTML(guidelinesHTML)
	} else {
		content, err := theme.LoadContent("templates/MetaLab-2026/guidelines.html")
		if err != nil {
			c.String(http.StatusInternalServerError, "加载准则失败")
			return
		}
		guidelines = content
	}
	c.HTML(http.StatusOK, "auth/register.html", common.BuildPageData(c, gin.H{
		"Title":               "注册",
		"ExtraCSS":            "/static/css/auth.css",
		"Guidelines":          guidelines,
		"RegistrationEnabled": ac.authService.IsRegistrationEnabled(),
	}))
}

// LoginPage 登录页面（已登录用户重定向到首页）
func (ac *AuthController) LoginPage(c *gin.Context) {
	if _, exists := c.Get("uid"); exists {
		c.Redirect(http.StatusFound, "/")
		return
	}
	c.HTML(http.StatusOK, "auth/login.html", common.BuildPageData(c, gin.H{
		"Title":    "登录",
		"ExtraCSS": "/static/css/auth.css",
	}))
}
