// Package notification 提供当前接收人的 PostgreSQL 站内通知读取投影。
package notification

import (
	"context"
	"strconv"
	"strings"
	"time"

	"gorm.io/gorm"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/internal/model/dto"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// Query 提供后台账号未读数和基础列表查询。
type Query struct {
	db  *gorm.DB
	now func() time.Time
}

// NewQuery 创建后台通知查询。
func NewQuery(db *gorm.DB) *Query {
	return &Query{db: db, now: time.Now}
}

// UnreadCount 从 PostgreSQL 查询当前后台账号的准确未读数。
func (q *Query) UnreadCount(ctx context.Context, recipientID uint) (*dto.NotificationUnreadCountResponse, error) {
	if recipientID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	var count int64
	now := q.now().UTC()
	err := q.db.WithContext(ctx).Model(&model.Notification{}).
		Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
			constants.NotificationRecipientKindAccount, recipientID, false, now).
		Count(&count).Error
	if err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读数失败")
	}
	return newUnreadCountResponse(count), nil
}

// List 按创建时间和 ID 倒序查询当前后台账号的未过期通知。
func (q *Query) List(ctx context.Context, recipientID uint, request dto.NotificationListRequest) (*dto.NotificationListResponse, error) {
	if recipientID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
	if err != nil {
		return nil, err
	}
	if !isNotificationCategory(request.Category) || !isNotificationSeverity(request.Severity) || len(request.Type) > 100 || strings.TrimSpace(request.Type) != request.Type {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	now := q.now().UTC()
	base := q.db.WithContext(ctx).Model(&model.Notification{}).
		Where("recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
			constants.NotificationRecipientKindAccount, recipientID, now)
	if request.Category != "" {
		base = base.Where("category = ?", request.Category)
	}
	if request.Type != "" {
		base = base.Where("type = ?", request.Type)
	}
	if request.Severity != "" {
		base = base.Where("severity = ?", request.Severity)
	}
	if request.IsRead != nil {
		base = base.Where("is_read = ?", *request.IsRead)
	}
	var total int64
	if err := base.Count(&total).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知总数失败")
	}
	var records []model.Notification
	if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知列表失败")
	}
	items := make([]dto.NotificationItem, 0, len(records))
	for _, record := range records {
		items = append(items, dto.NotificationItem{
			ID: record.ID, Category: record.Category, Type: record.Type, Severity: record.Severity,
			Title: record.Title, Body: record.Body, RefType: record.RefType, RefID: record.RefID,
			RefKey: record.RefKey, IsRead: record.IsRead, ReadAt: record.ReadAt, CreatedAt: record.CreatedAt,
		})
	}
	return &dto.NotificationListResponse{Items: items, Total: total, Page: page, Size: pageSize}, nil
}

// PersonalUnreadCount 查询当前个人客户可见业务通知的准确未读数。
func (q *Query) PersonalUnreadCount(ctx context.Context, customerID uint) (*dto.NotificationUnreadCountResponse, error) {
	if customerID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	var count int64
	err := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC()).
		Where("is_read = ?", false).
		Count(&count).Error
	if err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知未读数失败")
	}
	return newUnreadCountResponse(count), nil
}

// PersonalList 查询当前个人客户可见的未过期业务通知简化列表。
func (q *Query) PersonalList(ctx context.Context, customerID uint, request dto.PersonalNotificationListRequest) (*dto.PersonalNotificationListResponse, error) {
	if customerID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	page, pageSize, offset, err := normalizeNotificationPagination(request.Page, request.PageSize)
	if err != nil {
		return nil, err
	}
	base := personalNotificationScope(q.db.WithContext(ctx).Model(&model.Notification{}), customerID, q.now().UTC())
	if request.IsRead != nil {
		base = base.Where("is_read = ?", *request.IsRead)
	}
	var total int64
	if err := base.Count(&total).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知总数失败")
	}
	var records []model.Notification
	if err := base.Order("created_at DESC, id DESC").Offset(offset).Limit(pageSize).Find(&records).Error; err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询个人客户通知列表失败")
	}
	return &dto.PersonalNotificationListResponse{
		Items: notificationItems(records), Total: total, Page: page, Size: pageSize,
	}, nil
}

// UnreadSummary 使用单条 PostgreSQL 查询返回当前后台账号的固定分类汇总。
func (q *Query) UnreadSummary(ctx context.Context, recipientID uint) (*dto.NotificationUnreadSummaryResponse, error) {
	if recipientID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	var summary dto.NotificationUnreadSummaryResponse
	err := q.db.WithContext(ctx).Model(&model.Notification{}).
		Select(`COUNT(*) AS total,
			COUNT(*) FILTER (WHERE category = ?) AS approval,
			COUNT(*) FILTER (WHERE category = ?) AS expiry,
			COUNT(*) FILTER (WHERE category = ?) AS sync,
			COUNT(*) FILTER (WHERE category = ?) AS system`,
			constants.NotificationCategoryApproval,
			constants.NotificationCategoryExpiry,
			constants.NotificationCategorySync,
			constants.NotificationCategorySystem).
		Where("recipient_kind = ? AND recipient_id = ? AND is_read = ? AND (expires_at IS NULL OR expires_at > ?)",
			constants.NotificationRecipientKindAccount, recipientID, false, q.now().UTC()).
		Scan(&summary).Error
	if err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知未读汇总失败")
	}
	return &summary, nil
}

func isNotificationCategory(category string) bool {
	switch category {
	case "", constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry,
		constants.NotificationCategorySync, constants.NotificationCategorySystem:
		return true
	default:
		return false
	}
}

func isNotificationSeverity(severity string) bool {
	switch severity {
	case "", constants.NotificationSeverityInfo, constants.NotificationSeverityWarning,
		constants.NotificationSeverityError, constants.NotificationSeverityCritical:
		return true
	default:
		return false
	}
}

func normalizeNotificationPagination(page, pageSize int) (int, int, int, error) {
	if page <= 0 {
		page = 1
	}
	if page > constants.NotificationMaxPage {
		return 0, 0, 0, errors.New(errors.CodeInvalidParam)
	}
	if pageSize <= 0 {
		pageSize = constants.NotificationDefaultPageSize
	}
	if pageSize > constants.NotificationMaxPageSize {
		return 0, 0, 0, errors.New(errors.CodeInvalidParam)
	}
	return page, pageSize, (page - 1) * pageSize, nil
}

func personalNotificationScope(db *gorm.DB, customerID uint, now time.Time) *gorm.DB {
	return db.Where(`recipient_kind = ? AND recipient_id = ?
		AND category IN ? AND type IN ? AND (expires_at IS NULL OR expires_at > ?)`,
		constants.NotificationRecipientKindPersonalCustomer,
		customerID,
		[]string{constants.NotificationCategoryApproval, constants.NotificationCategoryExpiry, constants.NotificationCategorySystem},
		[]string{constants.NotificationTypePackageExpiring, constants.NotificationTypeExchangeShippingCreated},
		now,
	)
}

func newUnreadCountResponse(count int64) *dto.NotificationUnreadCountResponse {
	displayCount := strconv.FormatInt(count, 10)
	if count > 99 {
		displayCount = "99+"
	}
	return &dto.NotificationUnreadCountResponse{Count: count, DisplayCount: displayCount}
}

func notificationItems(records []model.Notification) []dto.NotificationItem {
	items := make([]dto.NotificationItem, 0, len(records))
	for _, record := range records {
		items = append(items, dto.NotificationItem{
			ID: record.ID, Category: record.Category, Type: record.Type, Severity: record.Severity,
			Title: record.Title, Body: record.Body, RefType: record.RefType, RefID: record.RefID,
			RefKey: record.RefKey, IsRead: record.IsRead, ReadAt: record.ReadAt, CreatedAt: record.CreatedAt,
		})
	}
	return items
}
