package notification

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hyapp-admin-server/internal/modules/shared"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/response"
)

type Handler struct {
	service *NotificationService
	audit   shared.OperationLogger
}

func New(store *repository.Store, audit shared.OperationLogger) *Handler {
	return &Handler{service: NewService(store), audit: audit}
}

func (h *Handler) ListNotifications(c *gin.Context) {
	items, err := h.service.ListNotifications()
	if err != nil {
		response.ServerError(c, "获取通知失败")
		return
	}
	response.OK(c, gin.H{"items": items, "unread": unreadCount(items)})
}

func (h *Handler) MarkNotificationRead(c *gin.Context) {
	id, ok := shared.ParseID(c, "id")
	if !ok {
		return
	}
	item, err := h.service.MarkNotificationRead(id)
	if err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "mark-notification-read", "admin_notifications", "success", fmt.Sprintf("notification_id=%d", id))
	response.OK(c, item)
}

func (h *Handler) MarkAllNotificationsRead(c *gin.Context) {
	updated, err := h.service.MarkAllNotificationsRead()
	if err != nil {
		response.ServerError(c, "标记通知失败")
		return
	}
	shared.OperationLog(c, h.audit, "mark-all-notifications-read", "admin_notifications", "success", fmt.Sprintf("%d notifications", updated))
	response.OK(c, gin.H{"updated": updated})
}

func (h *Handler) DeleteNotification(c *gin.Context) {
	id, ok := shared.ParseID(c, "id")
	if !ok {
		return
	}
	if err := h.service.DeleteNotification(id); err != nil {
		response.BadRequest(c, err.Error())
		return
	}
	shared.OperationLog(c, h.audit, "delete-notification", "admin_notifications", "success", fmt.Sprintf("notification_id=%d", id))
	response.OK(c, gin.H{"deleted": true})
}
