package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// 注册用户
func Register(cfg *Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req RegisterRequest
		err := c.ShouldBindJSON(&req)
		if err != nil {
			Logger.Error("参数错误", zap.Error(err))
			c.JSON(400, gin.H{
				"message": "参数错误",
			})
			return
		}

		// 验证邮箱
		if EmailExists(req.Email) {
			c.JSON(400, gin.H{
				"message": "邮箱已存在",
			})
			return
		}

		//密码加密
		hashedPassword, err := HashPassword(req.Password)
		if err != nil {
			Logger.Error("密码加密失败", zap.Error(err))
			c.JSON(500, gin.H{
				"message": "密码加密失败",
			})
			return
		}

		// 创建用户
		user := User{
			Name:     req.Name,
			Email:    req.Email,
			Password: hashedPassword,
			Phone:    req.Phone,
		}

		err = DB.Create(&user).Error
		if err != nil {
			Logger.Error("创建用户失败", zap.Error(err))
			c.JSON(500, gin.H{
				"message": "创建用户失败",
			})
			return
		}

		Logger.Info("用户注册成功", zap.String("email", req.Email))

		c.JSON(200, gin.H{
			"message": "用户注册成功",
		})
	}
}

// 登录
func Login(cfg *Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req LoginRequest

		err := c.ShouldBindJSON(&req)
		if err != nil {
			c.JSON(400, gin.H{"错误": err.Error()})
			return
		}

		//查找用户
		var user User
		err = DB.Where("email = ?", req.Email).First(&user).Error
		if err != nil {
			Logger.Warn("用户不存在", zap.String("email", req.Email))
			c.JSON(401, gin.H{"错误": "电子邮件或密码无效"})
			return
		}

		//验证密码
		if !VerifyPassword(user.Password, req.Password) {
			Logger.Warn("密码错误", zap.String("email", req.Email))
			c.JSON(401, gin.H{"错误": "电子邮件或密码无效"})
			return
		}

		//生成token
		token, err := GenerateToken(user.ID, user.Email, cfg.JWT.Secret, int64(cfg.JWT.Expire))

		if err != nil {
			Logger.Error("生成token失败", zap.Error(err))
			c.JSON(500, gin.H{"错误": "生成token失败"})
			return
		}

		Logger.Info("用户登录成功", zap.String("email", req.Email))

		c.JSON(200, LoginResponse{
			Token: token,
			User: User{
				ID:    user.ID,
				Name:  user.Name,
				Email: user.Email,
				Phone: user.Phone,
				Age:   user.Age,
			},
		})
	}
}

// 获取用户信息
func GetProfile(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var user User
	if err := DB.First(&user, userID.(uint)).Error; err != nil {
		c.JSON(404, gin.H{"error": "User not found"})
		return
	}

	c.JSON(200, user)
}

// 更新用户信息
func UpdateProfile(c *gin.Context) {
	userID, _ := c.Get("user_id")

	var req struct {
		Name  string `json:"name"`
		Phone string `json:"phone"`
		Age   int    `json:"age"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := DB.Model(&User{}).Where("id = ?", userID.(uint)).Updates(req).Error; err != nil {
		Logger.Error("Failed to update user", zap.Error(err))
		c.JSON(500, gin.H{"error": "Failed to update profile"})
		return
	}

	Logger.Info("User profile updated", zap.Uint("user_id", userID.(uint)))
	c.JSON(200, gin.H{"message": "Profile updated successfully"})
}

// 健康检查
func HealthCheck(c *gin.Context) {
	c.JSON(200, gin.H{
		"status": "ok",
		"app":    "AuthAPI",
	})
}
