package controller

import (
	"errors"
	"net/http"
	"strconv"

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

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

// Submit API 提交审核
func (ctrl *PostController) Submit(c *gin.Context) {
	uid, _, 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, err := ctrl.postService.GetByID(uint(id))
	if err != nil {
		common.Error(c, http.StatusNotFound, "帖子不存在")
		return
	}

	if post.UserID != uid {
		common.Error(c, http.StatusForbidden, "无权操作此帖子")
		return
	}

	if err := ctrl.postService.SubmitForAudit(uint(id)); err != nil {
		if errors.Is(err, common.ErrPostCannotSubmit) || errors.Is(err, common.ErrPostNotFound) {
			common.Error(c, http.StatusBadRequest, err.Error())
		} else {
			common.Error(c, http.StatusInternalServerError, "提交审核失败")
		}
		return
	}

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

// ListAPI 帖子列表 JSON API
func (ctrl *PostController) ListAPI(c *gin.Context) {
	keyword := c.Query("keyword")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))

	posts, total, err := ctrl.postService.List(keyword, page, pageSize)
	if err != nil {
		common.Error(c, http.StatusInternalServerError, "获取帖子列表失败")
		return
	}

	common.Ok(c, model.PostListResult{
		Items:      posts,
		Total:      total,
		Page:       page,
		TotalPages: common.PageCount(total, pageSize),
	})
}

// ShowAPI 帖子详情 JSON API
func (ctrl *PostController) ShowAPI(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil {
		common.Error(c, http.StatusBadRequest, "无效的帖子 ID")
		return
	}

	post, err := ctrl.postService.GetByID(uint(id))
	if err != nil {
		common.Error(c, http.StatusNotFound, "帖子不存在")
		return
	}

	uid, role, _ := common.GetGinUser(c)

	// 权限控制：非 approved 帖子仅作者和 moderator+ 可见
	if post.Status != model.PostStatusApproved {
		if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
			common.Error(c, http.StatusNotFound, "帖子不存在")
			return
		}
	}

	// 已登录用户阅读计数（已发布帖子，自动去重+防刷）
	if uid > 0 && post.Status == model.PostStatusApproved {
		ctrl.postService.RecordRead(uid, post.ID)
	}

	// 访客阅读计数（基于 Cookie 标识去重+防刷）
	if uid == 0 && post.Status == model.PostStatusApproved {
		vid := ctrl.getVisitorID(c)
		ctrl.postService.RecordGuestRead(vid, post.ID)
	}

	ctrl.applyShortcode(post)

	common.Ok(c, post)
}
