package handlers

import (
	"fmt"
	"strconv"

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

// GetUserProfile 获取公开用户资料
func GetUserProfile(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid user ID")
		return
	}

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

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

// GetUserPosts 获取用户已发布文章
func GetUserPosts(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 32)
	if err != nil {
		utils.Error(c, 400, "Invalid user ID")
		return
	}

	sort := c.DefaultQuery("sort", "recent")
	if sort != "recent" && sort != "popular" {
		sort = "recent"
	}

	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "5"))

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

	posts, err := repositories.GetPostsByUserID(uint(id), sort, limit)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.Success(c, repositories.BuildPostsResponse(posts))
}

// UpdateCurrentUser 更新当前用户资料
func UpdateCurrentUser(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		utils.Error(c, 401, "Unauthorized")
		return
	}

	var req models.UpdateProfileRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		return
	}

	if err := repositories.UpdateCurrentUserProfile(userID.(uint), &req); err != nil {
		utils.ServerError(c, err)
		return
	}

	user, err := repositories.GetUserByID(userID.(uint))
	if err != nil {
		utils.ServerError(c, err)
		return
	}

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

// UpdateCurrentUserPassword 修改当前用户密码
func UpdateCurrentUserPassword(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		utils.Error(c, 401, "Unauthorized")
		return
	}

	var req models.UpdatePasswordRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		utils.Error(c, 400, "Invalid request")
		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
	}

	if !utils.CheckPasswordHash(req.OldPassword, user.PasswordHash) {
		utils.Error(c, 400, "原密码不正确")
		return
	}

	hashedPassword, err := utils.HashPassword(req.NewPassword)
	if err != nil {
		utils.ServerError(c, err)
		return
	}

	if err := repositories.UpdateUserPassword(userID.(uint), hashedPassword); err != nil {
		utils.ServerError(c, err)
		return
	}

	utils.SuccessWithMsg(c, "Password updated successfully", nil)
}

// AdminGetUserProfile 管理员查看用户公开资料（复用公开结构）
func AdminGetUserProfile(c *gin.Context) {
	idStr := c.Param("id")
	var id uint
	if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
		utils.Error(c, 400, "Invalid user ID")
		return
	}

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

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