package packagepkg

import (
	"time"

	"github.com/break/junhong_cmp_fiber/internal/model"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"gorm.io/gorm"
)

// FindAttachableMainPackageForAddon 查询加油包可挂靠的主套餐。
// 已用完但未过期的主套餐仍可挂靠；已过期、已失效的主套餐不可挂靠。
func FindAttachableMainPackageForAddon(tx *gorm.DB, carrierType string, carrierID uint, now time.Time) (*model.PackageUsage, error) {
	var mainPackage model.PackageUsage
	query := tx.Model(&model.PackageUsage{}).
		Where("master_usage_id IS NULL").
		Where(
			"(status = ? OR (status IN ? AND (expires_at IS NULL OR expires_at > ?)))",
			constants.PackageUsageStatusPending,
			[]int{
				constants.PackageUsageStatusActive,
				constants.PackageUsageStatusDepleted,
			},
			now,
		).
		Order("priority ASC")

	switch carrierType {
	case constants.AssetWalletResourceTypeIotCard, "card":
		query = query.Where("iot_card_id = ?", carrierID)
	case constants.AssetWalletResourceTypeDevice:
		query = query.Where("device_id = ?", carrierID)
	default:
		return nil, gorm.ErrRecordNotFound
	}

	if err := query.First(&mainPackage).Error; err != nil {
		return nil, err
	}
	return &mainPackage, nil
}

// FindCurrentMainPackageForQueue 查询应让新主套餐排队的现有主套餐。
// 未过期的生效中、已用完主套餐仍占用当前周期；待生效只是队列记录，不阻止继续排队购买。
func FindCurrentMainPackageForQueue(tx *gorm.DB, carrierType string, carrierID uint, now time.Time) (*model.PackageUsage, error) {
	var mainPackage model.PackageUsage
	query := tx.Model(&model.PackageUsage{}).
		Where("master_usage_id IS NULL").
		Where("status IN ?", []int{
			constants.PackageUsageStatusActive,
			constants.PackageUsageStatusDepleted,
		}).
		Where("expires_at IS NULL OR expires_at > ?", now).
		Order("priority ASC, created_at ASC")

	switch carrierType {
	case constants.AssetWalletResourceTypeIotCard, "card":
		query = query.Where("iot_card_id = ?", carrierID)
	case constants.AssetWalletResourceTypeDevice:
		query = query.Where("device_id = ?", carrierID)
	default:
		return nil, gorm.ErrRecordNotFound
	}

	if err := query.First(&mainPackage).Error; err != nil {
		return nil, err
	}
	return &mainPackage, nil
}

// HasCurrentMainPackageForQueue 判断载体是否已有应让新主套餐排队的主套餐。
func HasCurrentMainPackageForQueue(tx *gorm.DB, carrierType string, carrierID uint, now time.Time) (bool, error) {
	_, err := FindCurrentMainPackageForQueue(tx, carrierType, carrierID, now)
	if err == nil {
		return true, nil
	}
	if err == gorm.ErrRecordNotFound {
		return false, nil
	}
	return false, err
}
