package handlers

import (
	"fmt"
	"net/http"
	"strings"

	"stock-user-system/internal/config"
	"stock-user-system/internal/middleware"
	"stock-user-system/internal/models"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type AuthHandler struct {
	DB  *gorm.DB
	CFG *config.Config
}

func (h *AuthHandler) Login(c *gin.Context) {
	var req struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "请求参数错误"})
		return
	}

	username := strings.ToLower(strings.TrimSpace(req.Username))

	var user models.User
	if err := h.DB.Preload("Role").Where("LOWER(username) = ?", username).First(&user).Error; err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "用户名或密码错误"})
		return
	}

	if user.Status != "active" {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "账号已被禁用"})
		return
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "用户名或密码错误"})
		return
	}

	token, err := middleware.GenerateToken(user.ID, user.Role.NameEnum(), h.CFG)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"success": false, "error": "internal server error"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"token": token,
		"user":  user.ToPublicInfo(),
	})
}

func (h *AuthHandler) Me(c *gin.Context) {
	current, ok := middleware.GetCurrentUser(c)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{"success": false, "error": "访问令牌无效或已过期"})
		return
	}

	var user models.User
	if err := h.DB.Preload("Role").Where("id = ?", current.ID).First(&user).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"success": false, "error": "not found"})
		return
	}

	c.JSON(http.StatusOK, user.ToPublicInfo())
}

func (h *AuthHandler) Logout(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"message": "登出成功"})
}

func hashPassword(password string) (string, error) {
	bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	return string(bytes), err
}

func validateUsername(username string) error {
	if len(username) < 3 || len(username) > 32 {
		return fmt.Errorf("用户名长度需在 3-32 位之间")
	}
	for _, r := range username {
		if !(r >= 'a' && r <= 'z') && !(r >= 'A' && r <= 'Z') && !(r >= '0' && r <= '9') && r != '_' && r != '-' {
			return fmt.Errorf("用户名只能包含字母、数字、下划线和短横线")
		}
	}
	return nil
}
