package notification

import (
	"context"
	"math"
	"strconv"

	"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"
	"github.com/break/junhong_cmp_fiber/pkg/middleware"
)

// Target 先校验通知属于当前账号，再解析白名单结构化目标并复核当前权限。
func (q *Query) Target(ctx context.Context, recipientID, notificationID uint) (*dto.NotificationTargetResponse, error) {
	result := &dto.NotificationTargetResponse{}
	if recipientID == 0 || notificationID == 0 {
		return nil, errors.New(errors.CodeInvalidParam)
	}
	var record model.Notification
	err := q.db.WithContext(ctx).Select("ref_type", "ref_id", "ref_key").
		Where("id = ? AND recipient_kind = ? AND recipient_id = ? AND (expires_at IS NULL OR expires_at > ?)",
			notificationID, constants.NotificationRecipientKindAccount, recipientID, q.now().UTC()).Take(&record).Error
	if err == gorm.ErrRecordNotFound {
		return result, nil
	}
	if err != nil {
		return nil, errors.Wrap(errors.CodeDatabaseError, err, "查询通知目标失败")
	}
	return q.resolveTarget(ctx, record)
}

func (q *Query) resolveTarget(ctx context.Context, record model.Notification) (*dto.NotificationTargetResponse, error) {
	definition, exists := notificationTargetDefinitions()[record.RefType]
	if !exists {
		return &dto.NotificationTargetResponse{}, nil
	}
	result := &dto.NotificationTargetResponse{TargetType: definition.targetType}
	if definition.keyTarget {
		result.TargetKey = record.RefKey
	}
	if definition.idTarget {
		id, valid := parseNotificationTargetID(record.RefID)
		if !valid {
			return result, nil
		}
		result.TargetID = &id
	}
	available, err := definition.available(q, ctx, record, result.TargetID)
	if err != nil {
		return nil, err
	}
	result.Available = available
	return result, nil
}

type targetDefinition struct {
	targetType string
	idTarget   bool
	keyTarget  bool
	available  func(*Query, context.Context, model.Notification, *uint) (bool, error)
}

func notificationTargetDefinitions() map[string]targetDefinition {
	return map[string]targetDefinition{
		constants.NotificationRefTypeRefund:         {targetType: constants.NotificationTargetTypeRefundDetail, idTarget: true, available: refundTargetAvailable},
		constants.NotificationRefTypeAgentRecharge:  {targetType: constants.NotificationTargetTypeAgentRechargeDetail, idTarget: true, available: unavailableFutureTarget},
		constants.NotificationRefTypeWeComApproval:  {targetType: constants.NotificationTargetTypeWeComApprovalDetail, idTarget: true, available: unavailableFutureTarget},
		constants.NotificationRefTypeIotCard:        {targetType: constants.NotificationTargetTypeIotCardDetail, idTarget: true, available: iotCardTargetAvailable},
		constants.NotificationRefTypeDevice:         {targetType: constants.NotificationTargetTypeDeviceDetail, idTarget: true, available: deviceTargetAvailable},
		constants.NotificationRefTypeExpiringAsset:  {targetType: constants.NotificationTargetTypeExpiringAssetList, idTarget: true, available: shopTargetAvailable},
		constants.NotificationRefTypeShopFund:       {targetType: constants.NotificationTargetTypeShopFundSummary, idTarget: true, available: shopTargetAvailable},
		constants.NotificationRefTypeIntegrationLog: {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
		constants.NotificationRefTypeCardSync:       {targetType: constants.NotificationTargetTypeIntegrationLog, keyTarget: true, available: integrationTargetAvailable},
		constants.NotificationRefTypeSystemConfig:   {targetType: constants.NotificationTargetTypeSystemConfig, keyTarget: true, available: systemConfigTargetAvailable},
	}
}

func parseNotificationTargetID(value string) (uint, bool) {
	parsed, err := strconv.ParseUint(value, 10, 64)
	if err != nil || parsed == 0 || parsed > math.MaxInt64 {
		return 0, false
	}
	return uint(parsed), true
}

func refundTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
	query := q.db.WithContext(ctx).Model(&model.RefundRequest{}).Where("id = ?", *id)
	switch middleware.GetUserTypeFromContext(ctx) {
	case constants.UserTypeSuperAdmin, constants.UserTypePlatform:
	case constants.UserTypeAgent:
		query = query.Where("creator = ?", middleware.GetUserIDFromContext(ctx))
	default:
		return false, nil
	}
	return targetExists(query, "查询退款通知目标失败")
}

func iotCardTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
	if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
		return false, nil
	}
	query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.IotCard{})).Where("id = ?", *id)
	return targetExists(query, "查询物联网卡通知目标失败")
}

func deviceTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
	if middleware.GetUserTypeFromContext(ctx) == constants.UserTypeEnterprise {
		return false, nil
	}
	query := middleware.ApplyShopFilter(ctx, q.db.WithContext(ctx).Model(&model.Device{})).Where("id = ?", *id)
	return targetExists(query, "查询设备通知目标失败")
}

func shopTargetAvailable(q *Query, ctx context.Context, _ model.Notification, id *uint) (bool, error) {
	if err := middleware.CanManageShop(ctx, *id); err != nil {
		return false, nil
	}
	query := middleware.ApplyShopIDFilter(ctx, q.db.WithContext(ctx).Model(&model.Shop{})).Where("id = ?", *id)
	return targetExists(query, "查询店铺通知目标失败")
}

func integrationTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
	userType := middleware.GetUserTypeFromContext(ctx)
	if userType != constants.UserTypeSuperAdmin && userType != constants.UserTypePlatform {
		return false, nil
	}
	if record.RefKey == "" {
		return false, nil
	}
	query := q.db.WithContext(ctx).Model(&model.IntegrationLog{}).Where("integration_id = ?", record.RefKey)
	return targetExists(query, "查询外部集成通知目标失败")
}

func systemConfigTargetAvailable(q *Query, ctx context.Context, record model.Notification, _ *uint) (bool, error) {
	if middleware.GetUserTypeFromContext(ctx) != constants.UserTypeSuperAdmin || record.RefKey == "" {
		return false, nil
	}
	query := q.db.WithContext(ctx).Model(&model.SystemConfig{}).Where("config_key = ?", record.RefKey)
	return targetExists(query, "查询系统配置通知目标失败")
}

func unavailableFutureTarget(_ *Query, _ context.Context, _ model.Notification, _ *uint) (bool, error) {
	return false, nil
}

func targetExists(query *gorm.DB, summary string) (bool, error) {
	var count int64
	if err := query.Count(&count).Error; err != nil {
		return false, errors.Wrap(errors.CodeDatabaseError, err, summary)
	}
	return count > 0, nil
}
