package hostagencypolicy

import (
	"strconv"

	"hyapp-admin-server/internal/model"
)

type policyDTO struct {
	ID                                uint       `json:"id"`
	AppCode                           string     `json:"app_code"`
	Name                              string     `json:"name"`
	PolicyType                        string     `json:"policy_type"`
	RegionID                          int64      `json:"region_id"`
	RegionIDs                         []int64    `json:"region_ids"`
	CycleKey                          string     `json:"cycle_key"`
	PolicyVersion                     uint64     `json:"policy_version"`
	Status                            string     `json:"status"`
	SettlementMode                    string     `json:"settlement_mode"`
	SettlementTriggerMode             string     `json:"settlement_trigger_mode"`
	GiftCoinToDiamondRatio            string     `json:"gift_coin_to_diamond_ratio"`
	PointDiamondsPerUSD               int64      `json:"point_diamonds_per_usd"`
	CoinsPerUSD                       int64      `json:"coins_per_usd"`
	MinimumWithdrawUSDMinor           int64      `json:"minimum_withdraw_usd_minor"`
	CoinSellerMinimumWithdrawUSDMinor int64      `json:"coin_seller_minimum_withdraw_usd_minor"`
	PlatformMinimumWithdrawUSDMinor   int64      `json:"platform_minimum_withdraw_usd_minor"`
	DiamondExchangeEnabled            bool       `json:"diamond_exchange_enabled"`
	WithdrawFeeBPS                    int32      `json:"withdraw_fee_bps"`
	AgencyPointShareBPS               int32      `json:"agency_point_share_bps"`
	ResidualDiamondToUSDRate          string     `json:"residual_diamond_to_usd_rate"`
	CoinSellerWithdrawalLimitPeriod   string     `json:"coin_seller_withdrawal_limit_period"`
	CoinSellerWithdrawalLimitCount    int64      `json:"coin_seller_withdrawal_limit_count"`
	PlatformWithdrawalLimitPeriod     string     `json:"platform_withdrawal_limit_period"`
	PlatformWithdrawalLimitCount      int64      `json:"platform_withdrawal_limit_count"`
	PlatformWithdrawalAllowedDays     []int32    `json:"platform_withdrawal_allowed_days"`
	Description                       string     `json:"description"`
	CreatedByAdminID                  uint       `json:"created_by_admin_id"`
	UpdatedByAdminID                  uint       `json:"updated_by_admin_id"`
	PublishStatus                     string     `json:"publish_status"`
	PublishError                      string     `json:"publish_error"`
	PublishedAtMS                     int64      `json:"published_at_ms"`
	PublishedByAdminID                uint       `json:"published_by_admin_id"`
	CopiedFromPolicyID                uint       `json:"copied_from_policy_id"`
	CopiedFromCycleKey                string     `json:"copied_from_cycle_key"`
	Inherited                         bool       `json:"inherited"`
	CreatedAtMS                       int64      `json:"created_at_ms"`
	UpdatedAtMS                       int64      `json:"updated_at_ms"`
	Levels                            []levelDTO `json:"levels"`
}

type levelDTO struct {
	ID               uint   `json:"id"`
	PolicyID         uint   `json:"policy_id"`
	Level            int32  `json:"level"`
	RequiredDiamonds int64  `json:"required_diamonds"`
	HostSalaryUSD    string `json:"host_salary_usd"`
	HostCoinReward   int64  `json:"host_coin_reward"`
	AgencySalaryUSD  string `json:"agency_salary_usd"`
	TotalSalaryUSD   string `json:"total_salary_usd"`
	Status           string `json:"status"`
	SortOrder        int32  `json:"sort_order"`
	CreatedAtMS      int64  `json:"created_at_ms"`
	UpdatedAtMS      int64  `json:"updated_at_ms"`
}

func policyFromModel(item model.HostAgencySalaryPolicy) policyDTO {
	coinSellerMinimum, platformMinimum := resolvedPolicyWithdrawalMinimums(item)
	levels := make([]levelDTO, 0, len(item.Levels))
	for _, level := range item.Levels {
		levels = append(levels, levelFromModel(level))
	}
	// 响应层只做展示友好的格式化：数据库 decimal 保留固定精度，接口去掉无意义尾零。
	return policyDTO{
		ID:                     item.ID,
		AppCode:                item.AppCode,
		Name:                   item.Name,
		PolicyType:             normalizePolicyType(item.PolicyType),
		RegionID:               item.RegionID,
		RegionIDs:              responseRegionIDs(item),
		CycleKey:               item.CycleKey,
		PolicyVersion:          item.PolicyVersion,
		Status:                 item.Status,
		SettlementMode:         item.SettlementMode,
		SettlementTriggerMode:  firstNonBlank(item.SettlementTriggerMode, settlementTriggerAutomatic),
		GiftCoinToDiamondRatio: trimDecimalZeros(item.GiftCoinToDiamondRatio),
		PointDiamondsPerUSD:    item.PointDiamondsPerUSD,
		CoinsPerUSD:            item.CoinsPerUSD,
		// 旧字段继续返回平台提现门槛，旧客户端不会因拆分字段而改变原展示和提交口径。
		MinimumWithdrawUSDMinor:           platformMinimum,
		CoinSellerMinimumWithdrawUSDMinor: coinSellerMinimum,
		PlatformMinimumWithdrawUSDMinor:   platformMinimum,
		DiamondExchangeEnabled:            item.DiamondExchangeEnabled,
		WithdrawFeeBPS:                    item.WithdrawFeeBPS,
		AgencyPointShareBPS:               item.AgencyPointShareBPS,
		ResidualDiamondToUSDRate:          trimDecimalZeros(item.ResidualDiamondToUSDRate),
		CoinSellerWithdrawalLimitPeriod:   firstNonBlank(item.CoinSellerWithdrawalLimitPeriod, withdrawalLimitPeriodMonth),
		CoinSellerWithdrawalLimitCount:    item.CoinSellerWithdrawalLimitCount,
		PlatformWithdrawalLimitPeriod:     firstNonBlank(item.PlatformWithdrawalLimitPeriod, withdrawalLimitPeriodMonth),
		PlatformWithdrawalLimitCount:      item.PlatformWithdrawalLimitCount,
		PlatformWithdrawalAllowedDays:     parseWithdrawalDays(item.PlatformWithdrawalAllowedDays),
		Description:                       item.Description,
		CreatedByAdminID:                  item.CreatedByAdminID,
		UpdatedByAdminID:                  item.UpdatedByAdminID,
		PublishStatus:                     firstNonBlank(item.PublishStatus, publishStatusDraft),
		PublishError:                      item.PublishError,
		PublishedAtMS:                     item.PublishedAtMS,
		PublishedByAdminID:                item.PublishedByAdminID,
		CopiedFromPolicyID:                item.CopiedFromPolicyID,
		CopiedFromCycleKey:                item.CopiedFromCycleKey,
		Inherited:                         item.CopiedFromPolicyID > 0 && item.CopiedFromCycleKey != "",
		CreatedAtMS:                       item.CreatedAtMS,
		UpdatedAtMS:                       item.UpdatedAtMS,
		Levels:                            levels,
	}
}

func responseRegionIDs(item model.HostAgencySalaryPolicy) []int64 {
	if len(item.RegionIDs) > 0 {
		return append([]int64(nil), item.RegionIDs...)
	}
	if item.RegionID > 0 {
		return []int64{item.RegionID}
	}
	return []int64{}
}

func levelFromModel(item model.HostAgencySalaryLevel) levelDTO {
	hostSalary := trimDecimalZeros(item.HostSalaryUSD)
	agencySalary := trimDecimalZeros(item.AgencySalaryUSD)
	// total_salary_usd 只是后台表格辅助展示字段，结算仍应分别读取主播工资和代理工资做各自入账。
	return levelDTO{
		ID:               item.ID,
		PolicyID:         item.PolicyID,
		Level:            item.LevelNo,
		RequiredDiamonds: item.RequiredDiamonds,
		HostSalaryUSD:    hostSalary,
		HostCoinReward:   item.HostCoinReward,
		AgencySalaryUSD:  agencySalary,
		TotalSalaryUSD:   formatCents(parseCentsOrZero(hostSalary) + parseCentsOrZero(agencySalary)),
		Status:           item.Status,
		SortOrder:        item.SortOrder,
		CreatedAtMS:      item.CreatedAtMS,
		UpdatedAtMS:      item.UpdatedAtMS,
	}
}

func parseCentsOrZero(value string) int64 {
	// 复用服务层 decimal parser，确保展示合计和入库金额使用同一套小数规则。
	_, cents, err := parseFixedDecimal(value, 2, true, "salary")
	if err != nil {
		return 0
	}
	return cents
}

func formatCents(value int64) string {
	whole := value / 100
	fraction := value % 100
	if fraction == 0 {
		return strconv.FormatInt(whole, 10)
	}
	return strconv.FormatInt(whole, 10) + "." + twoDigits(fraction)
}

func twoDigits(value int64) string {
	if value < 10 {
		return "0" + strconv.FormatInt(value, 10)
	}
	return strconv.FormatInt(value, 10)
}
