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"`
	RegionID                 int64      `json:"region_id"`
	Status                   string     `json:"status"`
	SettlementMode           string     `json:"settlement_mode"`
	SettlementTriggerMode    string     `json:"settlement_trigger_mode"`
	GiftCoinToDiamondRatio   string     `json:"gift_coin_to_diamond_ratio"`
	ResidualDiamondToUSDRate string     `json:"residual_diamond_to_usd_rate"`
	EffectiveFromMS          int64      `json:"effective_from_ms"`
	EffectiveToMS            int64      `json:"effective_to_ms"`
	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"`
	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 {
	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,
		RegionID:                 item.RegionID,
		Status:                   item.Status,
		SettlementMode:           item.SettlementMode,
		SettlementTriggerMode:    firstNonBlank(item.SettlementTriggerMode, settlementTriggerAutomatic),
		GiftCoinToDiamondRatio:   trimDecimalZeros(item.GiftCoinToDiamondRatio),
		ResidualDiamondToUSDRate: trimDecimalZeros(item.ResidualDiamondToUSDRate),
		EffectiveFromMS:          item.EffectiveFromMS,
		EffectiveToMS:            item.EffectiveToMS,
		Description:              item.Description,
		CreatedByAdminID:         item.CreatedByAdminID,
		UpdatedByAdminID:         item.UpdatedByAdminID,
		PublishStatus:            firstNonBlank(item.PublishStatus, publishStatusDraft),
		PublishError:             item.PublishError,
		PublishedAtMS:            item.PublishedAtMS,
		PublishedByAdminID:       item.PublishedByAdminID,
		CreatedAtMS:              item.CreatedAtMS,
		UpdatedAtMS:              item.UpdatedAtMS,
		Levels:                   levels,
	}
}

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)
}
