package admin

import (
	"math"
	"strconv"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"

	notificationapp "github.com/break/junhong_cmp_fiber/internal/application/notification"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	notificationquery "github.com/break/junhong_cmp_fiber/internal/query/notification"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	"github.com/break/junhong_cmp_fiber/pkg/logger"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
	"github.com/break/junhong_cmp_fiber/pkg/response"
	"go.uber.org/zap"
)

// NotificationHandler 提供当前后台账号的站内通知接口。
type NotificationHandler struct {
	query       *notificationquery.Query
	readService *notificationapp.ReadService
	validate    *validator.Validate
}

// NewNotificationHandler 创建后台站内通知 Handler。
func NewNotificationHandler(query *notificationquery.Query, readService *notificationapp.ReadService, validate *validator.Validate) *NotificationHandler {
	return &NotificationHandler{query: query, readService: readService, validate: validate}
}

// UnreadCount 查询当前后台账号的通知未读数。
// GET /api/admin/notifications/unread-count
func (h *NotificationHandler) UnreadCount(c *fiber.Ctx) error {
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	result, err := h.query.UnreadCount(c.UserContext(), recipientID)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// UnreadSummary 查询当前后台账号的固定分类未读汇总。
// GET /api/admin/notifications/unread-summary
func (h *NotificationHandler) UnreadSummary(c *fiber.Ctx) error {
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	result, err := h.query.UnreadSummary(c.UserContext(), recipientID)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// List 查询当前后台账号的未过期通知列表。
// GET /api/admin/notifications
func (h *NotificationHandler) List(c *fiber.Ctx) error {
	var request dto.NotificationListRequest
	if err := c.QueryParser(&request); err != nil {
		logNotificationListValidationFailure(c, request, err)
		return errors.New(errors.CodeInvalidParam)
	}
	if h.validate != nil {
		if err := h.validate.Struct(request); err != nil {
			logNotificationListValidationFailure(c, request, err)
			return errors.New(errors.CodeInvalidParam)
		}
	}
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	result, err := h.query.List(c.UserContext(), recipientID, request)
	if err != nil {
		return err
	}
	return response.SuccessWithPagination(c, result.Items, result.Total, result.Page, result.Size)
}

func logNotificationListValidationFailure(c *fiber.Ctx, request dto.NotificationListRequest, err error) {
	logger.GetAppLogger().Warn("站内通知列表参数验证失败",
		zap.String("method", c.Method()),
		zap.String("path", c.Path()),
		zap.Int("page", request.Page),
		zap.Int("page_size", request.PageSize),
		zap.Error(err),
	)
}

// MarkRead 将当前后台账号的一条通知幂等标记为已读。
// PUT /api/admin/notifications/:id/read
func (h *NotificationHandler) MarkRead(c *fiber.Ctx) error {
	notificationID, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil || notificationID == 0 || notificationID > math.MaxInt64 {
		return errors.New(errors.CodeInvalidParam)
	}
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	if err := h.readService.MarkRead(c.UserContext(), recipientID, uint(notificationID)); err != nil {
		return err
	}
	return response.Success(c, dto.NotificationReadResponse{Success: true})
}

// Target 解析当前后台账号通知的受控结构化目标。
// GET /api/admin/notifications/:id/target
func (h *NotificationHandler) Target(c *fiber.Ctx) error {
	notificationID, err := strconv.ParseUint(c.Params("id"), 10, 64)
	if err != nil || notificationID == 0 || notificationID > math.MaxInt64 {
		return errors.New(errors.CodeInvalidParam)
	}
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	result, err := h.query.Target(c.UserContext(), recipientID, uint(notificationID))
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

// MarkAllRead 将当前后台账号全部或指定类别通知幂等标记为已读。
// PUT /api/admin/notifications/read-all
func (h *NotificationHandler) MarkAllRead(c *fiber.Ctx) error {
	var request dto.NotificationReadAllRequest
	if len(c.Body()) > 0 {
		if err := c.BodyParser(&request); err != nil {
			logNotificationReadAllValidationFailure(c, request, err)
			return errors.New(errors.CodeInvalidParam)
		}
	}
	if h.validate != nil {
		if err := h.validate.Struct(request); err != nil {
			logNotificationReadAllValidationFailure(c, request, err)
			return errors.New(errors.CodeInvalidParam)
		}
	}
	recipientID := middleware.GetUserIDFromContext(c.UserContext())
	result, err := h.readService.MarkAllRead(c.UserContext(), recipientID, request)
	if err != nil {
		return err
	}
	return response.Success(c, result)
}

func logNotificationReadAllValidationFailure(c *fiber.Ctx, request dto.NotificationReadAllRequest, err error) {
	logger.GetAppLogger().Warn("站内通知批量已读参数验证失败",
		zap.String("method", c.Method()),
		zap.String("path", c.Path()),
		zap.Bool("category_present", request.Category != ""),
		zap.Error(err),
	)
}
