package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gouki/lunar-server/internal/config"
	"github.com/gouki/lunar-server/internal/model"
	"github.com/gouki/lunar-server/internal/service"
)

// UserLogin 用户登录
func UserLogin(c *gin.Context) {
	var req struct {
		Code string `json:"code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// TODO: 调用微信接口获取 openid
	// 这里模拟返回
	openID := "mock_openid_" + req.Code

	userService := service.NewUserService()
	user, err := userService.GetUserByOpenID(openID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "服务器错误",
		})
		return
	}

	// 如果用户不存在，创建新用户
	if user == nil {
		user = &model.User{
			OpenID:   openID,
			Nickname: "微信用户",
			Status:   1,
		}
		if err := userService.CreateUser(user); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "创建用户失败",
			})
			return
		}
	}

	// 生成 token
	cfg := config.Load()
	token, err := userService.GenerateToken(user.ID, cfg.JWT.Secret)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "生成token失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"token": token,
			"user":  user,
		},
	})
}

// UserLogout 用户登出
func UserLogout(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
	})
}

// GetUserProfile 获取用户资料
func GetUserProfile(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "未授权",
		})
		return
	}

	userService := service.NewUserService()
	user, err := userService.GetUserByID(userID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取用户信息失败",
		})
		return
	}

	profile, _ := userService.GetUserProfile(user.ID)

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"user":    user,
			"profile": profile,
		},
	})
}

// UpdateUserProfile 更新用户资料
func UpdateUserProfile(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code": 401,
			"msg":  "未授权",
		})
		return
	}

	var req struct {
		Nickname      string `json:"nickname"`
		Avatar        string `json:"avatar"`
		Gender        int    `json:"gender"`
		RealName      string `json:"realName"`
		Birthday      string `json:"birthday"`
		BirthTime     string `json:"birthTime"`
		Zodiac        string `json:"zodiac"`
		Constellation string `json:"constellation"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	userService := service.NewUserService()

	// 更新用户基本信息
	user, err := userService.GetUserByID(userID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "获取用户信息失败",
		})
		return
	}

	if req.Nickname != "" {
		user.Nickname = req.Nickname
	}
	if req.Avatar != "" {
		user.Avatar = req.Avatar
	}
	if req.Gender > 0 {
		user.Gender = req.Gender
	}

	if err := userService.UpdateUser(user); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新用户信息失败",
		})
		return
	}

	// 更新用户资料
	profile, _ := userService.GetUserProfile(user.ID)
	if profile == nil {
		profile = &model.UserProfile{
			UserID: user.ID,
		}
	}

	if req.RealName != "" {
		profile.RealName = req.RealName
	}
	if req.Birthday != "" {
		profile.Birthday = req.Birthday
	}
	if req.BirthTime != "" {
		profile.BirthTime = req.BirthTime
	}
	if req.Zodiac != "" {
		profile.Zodiac = req.Zodiac
	}
	if req.Constellation != "" {
		profile.Constellation = req.Constellation
	}

	if err := userService.UpdateUserProfile(profile); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新用户资料失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"user":    user,
			"profile": profile,
		},
	})
}

// WechatAuth 微信授权
func WechatAuth(c *gin.Context) {
	var req struct {
		Code string `json:"code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// TODO: 调用微信接口获取 openid 和 session_key
	// 这里模拟返回
	openID := "mock_openid_" + req.Code

	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"openid":     openID,
			"sessionKey": "mock_session_key",
		},
	})
}
