package controller

import (
	"log"
	"net/http"
	"strconv"
	"time"

	"metazone.cc/metalab/internal/common"

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

// Delete 删除帖子
func (ctrl *StudioController) Delete(c *gin.Context) {
	uid, role, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
		return
	}

	post, getErr := ctrl.postService.GetByID(uint(id))
	if getErr != nil {
		common.Error(c, http.StatusNotFound, "帖子不存在")
		return
	}
	if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
		common.Error(c, http.StatusForbidden, "无权操作此帖子")
		return
	}

	authorID := post.UserID

	if err := ctrl.postService.Delete(uint(id)); err != nil {
		common.Error(c, http.StatusInternalServerError, "删除失败")
		return
	}

	// 删稿扣作者域能（无视负数，有限重试后静默忽略）
	if ctrl.energySvc != nil {
		const maxRetries = 3
		backoff := 100 * time.Millisecond
		for i := 0; i < maxRetries; i++ {
			if err := ctrl.energySvc.DeductOnDeletePost(authorID, uint(id)); err == nil {
				break
			}
			if i < maxRetries-1 {
				time.Sleep(backoff)
				backoff *= 2
			} else {
				log.Printf("删稿扣域能失败(user=%d, post=%d): %v", authorID, id, err)
			}
		}
	}

	common.OkMessage(c, "删除成功")
}

// Submit 提交审核
func (ctrl *StudioController) Submit(c *gin.Context) {
	uid, role, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
		return
	}

	post, getErr := ctrl.postService.GetByID(uint(id))
	if getErr != nil {
		common.Error(c, http.StatusNotFound, "帖子不存在")
		return
	}
	if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
		common.Error(c, http.StatusForbidden, "无权操作此帖子")
		return
	}

	if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
		common.Error(c, http.StatusBadRequest, err.Error())
		return
	}

	common.OkMessage(c, "已提交审核")
}

// TrendsAPI 创作中心趋势数据 API GET /api/studio/trends?period=7d|30d|90d
func (ctrl *StudioController) TrendsAPI(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.Error(c, http.StatusUnauthorized, "请先登录")
		return
	}

	if ctrl.trendsSvc == nil {
		common.Error(c, http.StatusInternalServerError, "趋势服务不可用")
		return
	}

	period := c.DefaultQuery("period", "7d")
	var days int
	switch period {
	case "7d":
		days = 7
	case "30d":
		days = 30
	case "90d":
		days = 90
	default:
		common.Error(c, http.StatusBadRequest, "无效的时间范围，支持 7d/30d/90d")
		return
	}

	since := time.Now().AddDate(0, 0, -days).Format("2006-01-02")

	result, err := ctrl.trendsSvc.GetTrends(uid, since)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "获取趋势数据失败")
		return
	}

	common.Ok(c, result)
}
