package model

import (
	"encoding/json"

	"gorm.io/gorm"
)

// ShopSeriesAllocation 店铺系列分配模型
// 记录平台或上级代理授权给某代理店铺可销售的套餐系列，以及佣金上限配置
type ShopSeriesAllocation struct {
	gorm.Model
	BaseModel                `gorm:"embedded"`
	ShopID                   uint   `gorm:"column:shop_id;index;not null;comment:被分配的店铺ID" json:"shop_id"`
	SeriesID                 uint   `gorm:"column:series_id;index;not null;comment:套餐系列ID" json:"series_id"`
	AllocatorShopID          uint   `gorm:"column:allocator_shop_id;index;not null;default:0;comment:分配者店铺ID，0表示平台分配" json:"allocator_shop_id"`
	OneTimeCommissionAmount  int64  `gorm:"column:one_time_commission_amount;type:bigint;default:0;not null;comment:该代理能拿的一次性佣金金额上限（分），固定模式有效" json:"one_time_commission_amount"`
	CommissionTiersJSON      string `gorm:"column:commission_tiers_json;type:jsonb;default:'[]';not null;comment:梯度模式专属阶梯金额列表" json:"commission_tiers_json"`
	EnableForceRecharge      bool   `gorm:"column:enable_force_recharge;default:false;not null;comment:是否启用强制充值" json:"enable_force_recharge"`
	ForceRechargeAmount      int64  `gorm:"column:force_recharge_amount;type:bigint;default:0;not null;comment:强制充值金额（分）" json:"force_recharge_amount"`
	ForceRechargeTriggerType int    `gorm:"column:force_recharge_trigger_type;type:int;default:2;not null;comment:强充触发类型 1-单次充值 2-累计充值" json:"force_recharge_trigger_type"`
	Status                   int    `gorm:"column:status;type:int;default:1;not null;comment:状态 0=禁用 1=启用" json:"status"`
}

// TableName 指定表名
func (ShopSeriesAllocation) TableName() string {
	return "tb_shop_series_allocation"
}

// AllocationCommissionTier 代理专属梯度佣金档位（仅存金额，阈值和运算符从 PackageSeries 全局配置读取）
type AllocationCommissionTier struct {
	Threshold int64 `json:"threshold"` // 阈值（与 PackageSeries.Tiers 对应）
	Amount    int64 `json:"amount"`    // 该代理在此档位的佣金上限（分）
}

// GetCommissionTiers 解析梯度佣金阶梯列表
func (a *ShopSeriesAllocation) GetCommissionTiers() ([]AllocationCommissionTier, error) {
	if a.CommissionTiersJSON == "" || a.CommissionTiersJSON == "[]" {
		return []AllocationCommissionTier{}, nil
	}
	var tiers []AllocationCommissionTier
	if err := json.Unmarshal([]byte(a.CommissionTiersJSON), &tiers); err != nil {
		return nil, err
	}
	return tiers, nil
}

// SetCommissionTiers 序列化梯度佣金阶梯列表
func (a *ShopSeriesAllocation) SetCommissionTiers(tiers []AllocationCommissionTier) error {
	if len(tiers) == 0 {
		a.CommissionTiersJSON = "[]"
		return nil
	}
	data, err := json.Marshal(tiers)
	if err != nil {
		return err
	}
	a.CommissionTiersJSON = string(data)
	return nil
}
