package controller

import (
	"net/http"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"

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

// CheckEmail 检查邮箱是否已注册
func (ac *AuthController) CheckEmail(c *gin.Context) {
	var req model.CheckEmailRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "请提供有效的邮箱地址")
		return
	}

	exists, err := ac.authService.CheckEmail(req.Email)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "检查失败")
		return
	}

	common.Ok(c, gin.H{"exists": exists})
}

// Register 注册 API
func (ac *AuthController) Register(c *gin.Context) {
	var req model.RegisterRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "请检查输入："+err.Error())
		return
	}

	// 注册 IP 限流：1 分钟 5 次（原子检查+递增）
	regKey := clientIP(c) + ":register"
	regResult := ac.rateLimiter.AllowIP(regKey)
	if regResult.Blocked {
		common.Error(c, http.StatusTooManyRequests, "注册请求过于频繁，请稍后重试")
		return
	}

	user, err := ac.authService.Register(req, clientIP(c))
	if err != nil {
		// 失败计数已在 AllowIP 中原子递增，无需额外记录
		switch err {
		case common.ErrMaintenanceMode:
			common.Error(c, http.StatusForbidden, "社区正在维护中，暂不支持注册")
		case common.ErrEmailExists:
			common.Error(c, http.StatusConflict, "该邮箱已注册")
		case common.ErrWeakPassword:
			common.Error(c, http.StatusBadRequest, err.Error())
		case common.ErrRegistrationDisabled:
			common.Error(c, http.StatusForbidden, "注册功能已关闭")
		default:
			common.Error(c, http.StatusInternalServerError, "注册失败，请稍后重试")
		}
		return
	}

	// 注册成功 → 清除该 IP 的注册限流计数
	ac.rateLimiter.ClearIP(regKey)

	sid, err := ac.sessionManager.Create(user, req.RememberMe, clientIP(c), c.GetHeader("User-Agent"))
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "注册失败，请稍后重试")
		return
	}

	common.SetSessionCookie(c, sid, req.RememberMe, ac.cfg)

	common.OkWithMessage(c, user, "注册成功！欢迎加入 MetaLab")
}

// Logout 退出登录：删除服务端 session + 清除 Cookie
func (ac *AuthController) Logout(c *gin.Context) {
	if sid, err := c.Cookie(common.SessionCookieName); err == nil && sid != "" {
		_ = ac.sessionManager.Destroy(sid)
	}
	common.ClearSessionCookie(c, ac.cfg)
	common.OkMessage(c, "已退出登录")
}

// RefreshToken 检查登录状态并续期（session 模式下每次请求已自动续期，此端点用于前端显式检查）
func (ac *AuthController) RefreshToken(c *gin.Context) {
	sid, err := c.Cookie(common.SessionCookieName)
	if err != nil || sid == "" {
		common.Error(c, http.StatusUnauthorized, "请重新登录")
		return
	}

	s, err := ac.sessionManager.Validate(sid)
	if err != nil || s == nil {
		common.ClearSessionCookie(c, ac.cfg)
		common.Error(c, http.StatusUnauthorized, "登录凭证已失效，请重新登录")
		return
	}

	common.Ok(c, gin.H{
		"uid":      s.UserID,
		"email":    s.Email,
		"username": s.Username,
		"role":     s.Role,
	})
}
