package admin

import (
	"crypto/sha256"
	"fmt"

	"com.sclktx/m/v2/internal/common/model"
	"com.sclktx/m/v2/internal/common/response"
	"com.sclktx/m/v2/internal/common/utils"

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

type AdminAuthHandler struct {
	db          *gorm.DB
	jwtSecret   string
	expireHours int
}

func NewAdminAuthHandler(db *gorm.DB, jwtSecret string, expireHours int) *AdminAuthHandler {
	return &AdminAuthHandler{db: db, jwtSecret: jwtSecret, expireHours: expireHours}
}

type AdminLoginRequest struct {
	Account  string `json:"account" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// @Summary      管理员登录
// @Description  管理员账号密码登录，返回JWT token
// @Tags         管理员
// @Accept       json
// @Produce      json
// @Param        body  body      AdminLoginRequest  true  "管理员登录信息"
// @Success      200   {object}  response.Response{data=object{token=string,admin_id=uint,account=string,name=string,is_super=bool}}  "成功"
// @Router       /admin/login [post]

func (h *AdminAuthHandler) Login(c *gin.Context) {
	var req AdminLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "参数错误")
		return
	}

	var admin model.AdminUser
	if err := h.db.Where("account = ? AND status = 1", req.Account).First(&admin).Error; err != nil {
		response.Unauthorized(c, "账号或密码错误")
		return
	}

	hashed := fmt.Sprintf("%x", sha256.Sum256([]byte(req.Password)))
	if admin.Password != hashed {
		response.Unauthorized(c, "账号或密码错误")
		return
	}

	token, err := utils.GenerateAdminToken(admin.ID, admin.Account, h.jwtSecret, h.expireHours)
	if err != nil {
		response.InternalError(c, "生成令牌失败")
		return
	}

	response.Success(c, gin.H{
		"token":    token,
		"admin_id": admin.ID,
		"account":  admin.Account,
		"name":     admin.Name,
		"is_super": admin.IsSuper,
	})
}

// @Summary      获取管理员信息
// @Description  获取当前登录管理员的个人信息
// @Tags         管理员
// @Accept       json
// @Produce      json
// @Security     BearerAuth
// @Success      200  {object}  response.Response{data=object{id=uint,account=string,name=string,is_super=bool}}  "成功"
// @Router       /admin/profile [get]

func (h *AdminAuthHandler) GetProfile(c *gin.Context) {
	adminID, _ := c.Get("admin_id")
	var admin model.AdminUser
	if err := h.db.First(&admin, adminID).Error; err != nil {
		response.NotFound(c, "管理员不存在")
		return
	}
	response.Success(c, gin.H{
		"id":       admin.ID,
		"account":  admin.Account,
		"name":     admin.Name,
		"is_super": admin.IsSuper,
	})
}
