package controller

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"

	"github.com/gin-gonic/gin"
)

// UpdateProfile 修改个人资料（用户名 + 个性签名，需登录）
// 普通用户走审核流程，管理员及以上直接落库
func (sc *SettingsController) UpdateProfile(c *gin.Context) {
	uid, exists := c.Get("uid")
	if !exists {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	var req struct {
		Username string `json:"username"`
		Bio      string `json:"bio"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, http.StatusBadRequest, "参数错误")
		return
	}

	userID := uid.(uint)

	// 判断是否需要审核
	shouldAudit, err := sc.auditService.ShouldAudit(userID)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "操作失败")
		return
	}

	if shouldAudit {
		user, err := sc.authService.GetProfile(userID)
		if err != nil {
			common.Error(c, http.StatusInternalServerError, "操作失败")
			return
		}
		if err := sc.auditService.SubmitProfileChanges(userID, user, req.Username, req.Bio); err != nil {
			handleAuditSubmitError(c, err)
			return
		}
		common.OkMessage(c, "修改已提交审核，通过前当前信息保持不变")
		return
	}

	// 管理员及以上直接更新
	if err := sc.authService.UpdateProfile(userID, req.Username, req.Bio); err != nil {
		handleSettingsError(c, err)
		return
	}

	common.OkMessage(c, "个人资料已更新")
}

// UploadAvatar 上传头像（需登录，multipart/form-data）
// 普通用户走审核流程，管理员及以上直接更新
func (sc *SettingsController) UploadAvatar(c *gin.Context) {
	uid, exists := c.Get("uid")
	if !exists {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	file, header, err := c.Request.FormFile("avatar")
	if err != nil {
		common.Error(c, http.StatusBadRequest, "请选择文件")
		return
	}
	defer file.Close()

	// 裁切参数（可选，来自前端裁切弹窗）
	cropX, _ := strconv.Atoi(c.PostForm("crop_x"))
	cropY, _ := strconv.Atoi(c.PostForm("crop_y"))
	cropSize, _ := strconv.Atoi(c.PostForm("crop_size"))

	userID := uid.(uint)

	// 判断是否需要审核
	shouldAudit, err := sc.auditService.ShouldAudit(userID)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "操作失败")
		return
	}

	if shouldAudit {
		// 仅处理图片，不更新用户
		avatarURL, err := sc.avatarService.ProcessImage(userID, file, header.Header.Get("Content-Type"), cropX, cropY, cropSize)
		if err != nil {
			common.Error(c, http.StatusBadRequest, err.Error())
			return
		}
		if err := sc.auditService.Submit(userID, model.AuditTypeAvatar, avatarURL); err != nil {
			handleAuditSubmitError(c, err)
			return
		}
		common.OkMessage(c, "头像已提交审核，通过前当前头像保持不变")
		return
	}

	// 管理员及以上直接更新
	url, err := sc.avatarService.ProcessAvatar(userID, file, header.Header.Get("Content-Type"), cropX, cropY, cropSize)
	if err != nil {
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	common.Ok(c, gin.H{"url": url})
}
