package announcement

import (
	"errors"
	"strconv"

	"hfb_sys/backend/internal/middleware"
	"hfb_sys/backend/pkg/response"

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

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

// List 获取公告列表（前台用户）
func (h *Handler) List(c *gin.Context) {
	query := AnnouncementListQuery{
		Category: c.Query("category"),
		Status:   "published",
	}
	query.Page, query.PageSize = parsePagination(c)

	result, err := h.service.List(c.Request.Context(), query)
	if err != nil {
		response.InternalServerError(c, "获取公告列表失败")
		return
	}

	response.OK(c, result)
}

// GetByID 获取公告详情
func (h *Handler) GetByID(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	announcement, err := h.service.GetByID(c.Request.Context(), id)
	if err != nil {
		if errors.Is(err, ErrNotFound) {
			response.NotFound(c, "公告不存在")
			return
		}
		response.InternalServerError(c, "获取公告失败")
		return
	}

	response.OK(c, announcement)
}

// AdminList 管理员获取公告列表
func (h *Handler) AdminList(c *gin.Context) {
	query := AnnouncementListQuery{
		Category: c.Query("category"),
		Status:   c.Query("status"),
	}
	query.Page, query.PageSize = parsePagination(c)

	result, err := h.service.AdminList(c.Request.Context(), query)
	if err != nil {
		response.InternalServerError(c, "获取公告列表失败")
		return
	}

	response.OK(c, result)
}

// AdminGetByID 管理员获取公告详情
func (h *Handler) AdminGetByID(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	announcement, err := h.service.AdminGetByID(c.Request.Context(), id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			response.NotFound(c, "公告不存在")
			return
		}
		response.InternalServerError(c, "获取公告失败")
		return
	}

	response.OK(c, announcement)
}

// Create 创建公告
func (h *Handler) Create(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "未授权")
		return
	}

	var req CreateAnnouncementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数不正确")
		return
	}

	announcement, err := h.service.Create(c.Request.Context(), req, adminID)
	if err != nil {
		response.InternalServerError(c, "创建公告失败")
		return
	}

	response.OK(c, announcement)
}

// Update 更新公告
func (h *Handler) Update(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	var req UpdateAnnouncementRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		response.BadRequest(c, "请求参数不正确")
		return
	}

	announcement, err := h.service.Update(c.Request.Context(), id, req)
	if err != nil {
		response.InternalServerError(c, "更新公告失败")
		return
	}

	response.OK(c, announcement)
}

// Publish 发布公告
func (h *Handler) Publish(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	if err := h.service.Publish(c.Request.Context(), id); err != nil {
		response.InternalServerError(c, "发布公告失败")
		return
	}

	response.OK(c, gin.H{"message": "发布成功"})
}

// Archive 归档公告
func (h *Handler) Archive(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	if err := h.service.Archive(c.Request.Context(), id); err != nil {
		response.InternalServerError(c, "归档公告失败")
		return
	}

	response.OK(c, gin.H{"message": "归档成功"})
}

// Unarchive 取消归档公告
func (h *Handler) Unarchive(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	if err := h.service.Unarchive(c.Request.Context(), id); err != nil {
		response.InternalServerError(c, "取消归档公告失败")
		return
	}

	response.OK(c, gin.H{"message": "取消归档成功"})
}

// Delete 删除公告
func (h *Handler) Delete(c *gin.Context) {
	id, err := parseID(c)
	if err != nil {
		response.BadRequest(c, "公告ID不正确")
		return
	}

	if err := h.service.Delete(c.Request.Context(), id); err != nil {
		response.InternalServerError(c, "删除公告失败")
		return
	}

	response.OK(c, gin.H{"message": "删除成功"})
}

// 工具函数

func parseID(c *gin.Context) (uint64, error) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil || id == 0 {
		return 0, errors.New("无效的ID")
	}
	return id, nil
}

func parsePagination(c *gin.Context) (int, int) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 20
	}
	if pageSize > 100 {
		pageSize = 100
	}
	return page, pageSize
}

func currentAdminID(c *gin.Context) (uint64, bool) {
	value, ok := c.Get(middleware.ContextAdminID)
	if !ok {
		return 0, false
	}
	adminID, ok := value.(uint64)
	return adminID, ok
}
