package handlers

import (
	"fmt"

	"github.com/gin-gonic/gin"
	"github.com/niangaodev/art-code/middleware"
	"github.com/niangaodev/art-code/models"
	"github.com/niangaodev/art-code/repositories"
	"github.com/niangaodev/art-code/utils"
)

// Login 请求结构
type LoginRequest struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

// Login 登录
func Login(c *gin.Context) {
	var req LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	// 获取用户
	user, err := repositories.GetUserByUsername(req.Username)
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if user == nil {
		utils.Error(c, 401, "Invalid username or password")
		return
	}

	// 验证密码
	if !utils.CheckPasswordHash(req.Password, user.PasswordHash) {
		utils.Error(c, 401, "Invalid username or password")
		return
	}

	// 生成JWT Token
	tokenString, expireUnix, err := middleware.GenerateToken(user.ID, user.Username, user.Role)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	// 记录登录日志
	go func() {
		ip := c.ClientIP()
		location := utils.GetRegion(ip)
		logEntry := &models.UserAccessLog{
			UserID:       user.ID,
			UserIP:       ip,
			UserLocation: location,
		}
		if err := repositories.CreateUserAccessLog(logEntry); err != nil {
			fmt.Printf("Failed to create login log: %v\n", err)
		}
	}()

	utils.Success(c, gin.H{
		"token":  tokenString,
		"expire": expireUnix,
		"user":   repositories.BuildUserResponse(user),
	})
}

// GetCurrentUser 获取当前用户信息
func GetCurrentUser(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		utils.Error(c, 401, "Unauthorized")
		return
	}

	user, err := repositories.GetUserByID(userID.(uint))
	if err != nil {
		utils.ServerError(c, err)
		return
	}
	if user == nil {
		utils.Error(c, 404, "User not found")
		return
	}

	utils.Success(c, repositories.BuildUserResponse(user))
}
