package controller

import (
	"net/http"
	"strconv"

	"metazone.cc/metalab/internal/common"

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

// WritePage 写文章页面
func (ctrl *StudioController) WritePage(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.RedirectToLogin(c)
		return
	}

	// 支持编辑模式：传入 post_id 参数
	postIDStr := c.Query("id")
	if postIDStr != "" {
		id, err := strconv.ParseUint(postIDStr, 10, 64)
		if err == nil {
			post, err := ctrl.postService.GetByID(uint(id))
			if err == nil {
				_, role, _ := common.GetGinUser(c)
				if !ctrl.postService.IsPostAccessible(uid, role, post.UserID) {
					c.HTML(http.StatusNotFound, "posts/404.html", common.BuildPageData(c, gin.H{
						"Title": "未找到",
					}))
					return
				}
				c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
					"Title":     "编辑文章 - 创作中心",
					"Post":      post,
					"ActiveTab": "write",
					"ExtraCSS":  "/static/css/studio.css",
				}))
				return
			}
		}
	}

	c.HTML(http.StatusOK, "studio/write.html", common.BuildPageData(c, gin.H{
		"Title":     "写文章 - 创作中心",
		"ActiveTab": "write",
		"ExtraCSS":  "/static/css/studio.css",
	}))
}

// AnalyticsPage 数据分析页面
func (ctrl *StudioController) AnalyticsPage(c *gin.Context) {
	uid, _, ok := common.GetGinUser(c)
	if !ok {
		common.RedirectToLogin(c)
		return
	}

	overview, err := ctrl.postService.GetOverview(uid)
	if err != nil {
		c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
			"Title":     "数据分析 - 创作中心",
			"Error":     "加载失败",
			"ActiveTab": "analytics",
			"ExtraCSS":  "/static/css/studio.css",
		}))
		return
	}

	c.HTML(http.StatusOK, "studio/analytics.html", common.BuildPageData(c, gin.H{
		"Title":     "数据分析 - 创作中心",
		"Overview":  overview,
		"ActiveTab": "analytics",
		"ExtraCSS":  "/static/css/studio.css",
	}))
}
