package teamsalarypolicy

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

type policyDTO struct {
	ID                    uint       `json:"id"`
	AppCode               string     `json:"app_code"`
	PolicyType            string     `json:"policy_type"`
	Name                  string     `json:"name"`
	RegionID              int64      `json:"region_id"`
	Status                string     `json:"status"`
	SettlementTriggerMode string     `json:"settlement_trigger_mode"`
	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"`
	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"`
	ThresholdUSD string `json:"threshold_usd"`
	RatePercent  string `json:"rate_percent"`
	SalaryUSD    string `json:"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.TeamSalaryPolicy) policyDTO {
	levels := make([]levelDTO, 0, len(item.Levels))
	for _, level := range item.Levels {
		levels = append(levels, levelFromModel(level))
	}
	// 响应层去掉 decimal 尾零，前端输入框仍以字符串处理金额和百分比，避免 JS 浮点误差。
	return policyDTO{
		ID:                    item.ID,
		AppCode:               item.AppCode,
		PolicyType:            item.PolicyType,
		Name:                  item.Name,
		RegionID:              item.RegionID,
		Status:                item.Status,
		SettlementTriggerMode: firstNonBlank(item.SettlementTriggerMode, settlementTriggerAutomatic),
		EffectiveFromMS:       item.EffectiveFromMS,
		EffectiveToMS:         item.EffectiveToMS,
		Description:           item.Description,
		CreatedByAdminID:      item.CreatedByAdminID,
		UpdatedByAdminID:      item.UpdatedByAdminID,
		CreatedAtMS:           item.CreatedAtMS,
		UpdatedAtMS:           item.UpdatedAtMS,
		Levels:                levels,
	}
}

func levelFromModel(item model.TeamSalaryLevel) levelDTO {
	return levelDTO{
		ID:           item.ID,
		PolicyID:     item.PolicyID,
		Level:        item.LevelNo,
		ThresholdUSD: trimDecimalZeros(item.ThresholdUSD),
		RatePercent:  trimDecimalZeros(item.RatePercent),
		SalaryUSD:    trimDecimalZeros(item.SalaryUSD),
		Status:       item.Status,
		SortOrder:    item.SortOrder,
		CreatedAtMS:  item.CreatedAtMS,
		UpdatedAtMS:  item.UpdatedAtMS,
	}
}
