package adminnotification

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

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

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

type Handler struct {
	service *Service
}

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

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 (h *Handler) List(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	page, pageSize := parsePagination(c)
	result, err := h.service.List(c.Request.Context(), Query{
		AdminUserID: adminID,
		OnlyUnread:  c.Query("read") == "unread",
		Page:        page,
		PageSize:    pageSize,
	})
	if err != nil {
		writeNotificationError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) UnreadCount(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	result, err := h.service.UnreadCount(c.Request.Context(), adminID)
	if err != nil {
		writeNotificationError(c, err)
		return
	}
	response.OK(c, result)
}

func (h *Handler) MarkRead(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	id, err := strconv.ParseUint(c.Param("id"), 10, 64)
	if err != nil || id == 0 {
		response.BadRequest(c, "ID 不正确")
		return
	}
	if err := h.service.MarkRead(c.Request.Context(), adminID, id); err != nil {
		writeNotificationError(c, err)
		return
	}
	response.OK(c, gin.H{"read": true})
}

func (h *Handler) MarkAllRead(c *gin.Context) {
	adminID, ok := currentAdminID(c)
	if !ok {
		response.Unauthorized(c, "缺少管理员上下文")
		return
	}
	count, err := h.service.MarkAllRead(c.Request.Context(), adminID)
	if err != nil {
		writeNotificationError(c, err)
		return
	}
	response.OK(c, gin.H{"read_count": count})
}

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
}

func writeNotificationError(c *gin.Context, err error) {
	switch {
	case errors.Is(err, ErrDependencyUnavailable):
		response.ServiceUnavailable(c, "数据库未连接")
	case errors.Is(err, ErrNotificationNotFound):
		response.NotFound(c, "通知不存在")
	default:
		response.Error(c, http.StatusInternalServerError, "internal_error", "通知服务暂时不可用")
	}
}
