// Package notification 提供站内通知简单写用例与 Outbox 消费边界。
package notification

import (
	"context"
	"strings"
	"time"

	"github.com/bytedance/sonic"
	"go.uber.org/zap"

	"github.com/break/junhong_cmp_fiber/internal/infrastructure/messaging/outbox"
	notificationinfra "github.com/break/junhong_cmp_fiber/internal/infrastructure/notification"
	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
)

// AdminDirectPayload 是明确后台账号通知的结构化 Outbox 载荷。
type AdminDirectPayload struct {
	RecipientID      uint              `json:"recipient_id"`
	NotificationType string            `json:"notification_type"`
	TemplateData     map[string]string `json:"template_data"`
	RefType          string            `json:"ref_type,omitempty"`
	RefID            string            `json:"ref_id,omitempty"`
	RefKey           string            `json:"ref_key,omitempty"`
	ExpiresAt        *time.Time        `json:"expires_at,omitempty"`
}

// PersonalCustomerDirectPayload 是明确个人客户通知的结构化 Outbox 载荷。
type PersonalCustomerDirectPayload = AdminDirectPayload

// AdminDynamicPayload 是按账号、平台角色或店铺动态解析后台接收人的结构化 Outbox 载荷。
type AdminDynamicPayload struct {
	TargetKind       string            `json:"target_kind"`
	TargetID         uint              `json:"target_id"`
	NotificationType string            `json:"notification_type"`
	TemplateData     map[string]string `json:"template_data"`
	RefType          string            `json:"ref_type,omitempty"`
	RefID            string            `json:"ref_id,omitempty"`
	RefKey           string            `json:"ref_key,omitempty"`
	ExpiresAt        *time.Time        `json:"expires_at,omitempty"`
}

type deliveryRequest struct {
	notificationType string
	templateData     map[string]string
	refType          string
	refID            string
	refKey           string
	expiresAt        *time.Time
}

// DeliveryService 校验接收人并幂等生成站内通知。
type DeliveryService struct {
	repository *notificationinfra.Repository
	registry   *notificationinfra.Registry
	resolver   DynamicRecipientResolver
	logger     *zap.Logger
	now        func() time.Time
}

// NewDeliveryService 创建站内通知投递用例。
func NewDeliveryService(repository *notificationinfra.Repository, registry *notificationinfra.Registry, resolver DynamicRecipientResolver, logger *zap.Logger) *DeliveryService {
	if logger == nil {
		logger = zap.NewNop()
	}
	return &DeliveryService{repository: repository, registry: registry, resolver: resolver, logger: logger, now: time.Now}
}

// Consume 消费明确或动态接收人通知事件；所有可恢复错误交给 Asynq 重试策略处理。
func (s *DeliveryService) Consume(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
	if envelope.PayloadVersion != constants.NotificationPayloadVersionV1 {
		return errors.New(errors.CodeInvalidParam, "通知事件类型或载荷版本不受支持")
	}
	if envelope.EventType == constants.OutboxEventTypeAdminDynamicNotification {
		return s.consumeDynamic(ctx, envelope)
	}
	return s.consumeDirect(ctx, envelope)
}

func (s *DeliveryService) consumeDirect(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
	recipientKind, err := recipientKindForDirectEvent(envelope.EventType)
	if err != nil {
		return err
	}
	var payload AdminDirectPayload
	if err := sonic.Unmarshal(envelope.Payload, &payload); err != nil {
		return errors.Wrap(errors.CodeInvalidParam, err, "通知事件载荷格式错误")
	}
	if payload.RecipientID == 0 || payload.NotificationType == "" {
		return errors.New(errors.CodeInvalidParam, "通知事件载荷不完整")
	}
	request := deliveryRequest{
		notificationType: payload.NotificationType, templateData: payload.TemplateData,
		refType: payload.RefType, refID: payload.RefID, refKey: payload.RefKey, expiresAt: payload.ExpiresAt,
	}
	if err := validateDeliveryRequest(request); err != nil {
		return err
	}
	return s.deliver(ctx, envelope.EventID, recipientKind, []uint{payload.RecipientID}, request)
}

func (s *DeliveryService) consumeDynamic(ctx context.Context, envelope outbox.DeliveryEnvelope) error {
	var payload AdminDynamicPayload
	if err := sonic.Unmarshal(envelope.Payload, &payload); err != nil {
		return errors.Wrap(errors.CodeInvalidParam, err, "通知事件载荷格式错误")
	}
	if payload.TargetKind == "" || payload.TargetID == 0 || payload.NotificationType == "" {
		return errors.New(errors.CodeInvalidParam, "通知事件载荷不完整")
	}
	if s.resolver == nil {
		return errors.New(errors.CodeInternalError, "通知动态接收人解析器未配置")
	}
	request := deliveryRequest{
		notificationType: payload.NotificationType, templateData: payload.TemplateData,
		refType: payload.RefType, refID: payload.RefID, refKey: payload.RefKey, expiresAt: payload.ExpiresAt,
	}
	if err := validateDeliveryRequest(request); err != nil {
		return err
	}
	recipientIDs, err := s.resolver.Resolve(ctx, payload.TargetKind, payload.TargetID)
	if err != nil {
		s.logger.Error("站内通知接收人解析失败",
			zap.String("event_id", envelope.EventID), zap.String("notification_type", payload.NotificationType),
			zap.String("target_kind", payload.TargetKind), zap.Uint("target_id", payload.TargetID),
			zap.String("failure_category", "recipient_resolution"))
		return err
	}
	if len(recipientIDs) == 0 {
		s.logger.Info("站内通知暂无可用接收人，已正常结束",
			zap.String("event_id", envelope.EventID), zap.String("target_kind", payload.TargetKind), zap.Uint("target_id", payload.TargetID),
			zap.String("resolution", "no_recipient"))
		return nil
	}
	return s.deliver(ctx, envelope.EventID, constants.NotificationRecipientKindAccount, recipientIDs, request)
}

func validateDeliveryRequest(request deliveryRequest) error {
	if strings.Contains(request.refID, "://") || strings.Contains(request.refKey, "://") {
		return errors.New(errors.CodeInvalidParam, "通知资源引用禁止包含任意 URL")
	}
	if request.refType == "" && (request.refID != "" || request.refKey != "") {
		return errors.New(errors.CodeInvalidParam, "通知资源引用缺少受控类型")
	}
	if request.refType != "" && request.refID == "" && request.refKey == "" {
		return errors.New(errors.CodeInvalidParam, "通知资源引用缺少定位值")
	}
	return nil
}

func (s *DeliveryService) deliver(ctx context.Context, eventID, recipientKind string, recipientIDs []uint, request deliveryRequest) error {
	rendered, err := s.registry.Render(request.notificationType, request.templateData, request.refType, recipientKind)
	if err != nil {
		s.logger.Error("站内通知模板校验失败",
			zap.String("event_id", eventID), zap.String("notification_type", request.notificationType),
			zap.String("failure_category", "template"))
		return errors.Wrap(errors.CodeInvalidParam, err, "站内通知模板校验失败")
	}
	now := s.now().UTC()
	expiresAt, err := notificationDisplayExpiry(rendered.Category, request.expiresAt, now)
	if err != nil {
		s.logger.Error("站内通知展示期限校验失败",
			zap.String("event_id", eventID), zap.String("notification_type", request.notificationType),
			zap.String("failure_category", "display_policy"))
		return err
	}
	for _, recipientID := range recipientIDs {
		active, err := s.isActiveRecipient(ctx, recipientKind, recipientID)
		if err != nil {
			return errors.Wrap(errors.CodeDatabaseError, err, "校验通知接收人失败")
		}
		if !active {
			s.logger.Info("站内通知接收人不可用，已跳过",
				zap.String("event_id", eventID), zap.String("recipient_kind", recipientKind), zap.Uint("recipient_id", recipientID))
			continue
		}
		notification := &model.Notification{
			EventID: eventID, RecipientKind: recipientKind,
			RecipientID: recipientID, Category: rendered.Category, Type: rendered.Type,
			Severity: rendered.Severity, Title: rendered.Title, Body: rendered.Body,
			RefType: request.refType, RefID: request.refID, RefKey: request.refKey,
			ExpiresAt: expiresAt, CreatedAt: now,
		}
		created, err := s.repository.CreateIdempotent(ctx, notification)
		if err != nil {
			return errors.Wrap(errors.CodeDatabaseError, err, "写入站内通知失败")
		}
		if !created {
			s.logger.Info("站内通知重复事件已幂等忽略",
				zap.String("event_id", eventID), zap.String("recipient_kind", recipientKind), zap.Uint("recipient_id", recipientID))
		}
	}
	return nil
}

func notificationDisplayExpiry(category string, requested *time.Time, now time.Time) (*time.Time, error) {
	switch category {
	case constants.NotificationCategoryApproval:
		return nil, nil
	case constants.NotificationCategoryExpiry:
		if requested == nil {
			return nil, errors.New(errors.CodeInvalidParam, "临期通知缺少业务到期时间")
		}
		expiresAt := requested.UTC()
		return &expiresAt, nil
	case constants.NotificationCategorySync:
		return cappedNotificationExpiry(requested, now, constants.NotificationSyncDisplayDays), nil
	case constants.NotificationCategorySystem:
		return cappedNotificationExpiry(requested, now, constants.NotificationSystemMaxDisplayDays), nil
	default:
		return nil, errors.New(errors.CodeInvalidParam, "通知类别不支持展示期限策略")
	}
}

func cappedNotificationExpiry(requested *time.Time, now time.Time, maxDays int) *time.Time {
	maximum := now.AddDate(0, 0, maxDays)
	if requested == nil {
		if maxDays == constants.NotificationSystemMaxDisplayDays {
			defaultExpiry := now.AddDate(0, 0, constants.NotificationSystemDefaultDisplayDays)
			return &defaultExpiry
		}
		return &maximum
	}
	expiresAt := requested.UTC()
	if expiresAt.After(maximum) {
		expiresAt = maximum
	}
	return &expiresAt
}

func recipientKindForDirectEvent(eventType string) (string, error) {
	switch eventType {
	case constants.OutboxEventTypeAdminDirectNotification:
		return constants.NotificationRecipientKindAccount, nil
	case constants.OutboxEventTypePersonalCustomerDirectNotification:
		return constants.NotificationRecipientKindPersonalCustomer, nil
	default:
		return "", errors.New(errors.CodeInvalidParam, "通知事件类型或载荷版本不受支持")
	}
}

func (s *DeliveryService) isActiveRecipient(ctx context.Context, recipientKind string, recipientID uint) (bool, error) {
	switch recipientKind {
	case constants.NotificationRecipientKindAccount:
		return s.repository.IsActiveAccount(ctx, recipientID)
	case constants.NotificationRecipientKindPersonalCustomer:
		return s.repository.IsActivePersonalCustomer(ctx, recipientID)
	default:
		return false, nil
	}
}
