package hostsalarysettlement

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"hyapp-admin-server/internal/modules/shared"
)

type settlementUserID int64

func (v *settlementUserID) UnmarshalJSON(data []byte) error {
	raw := strings.TrimSpace(string(data))
	if raw == "" || raw == "null" {
		*v = 0
		return nil
	}
	if strings.HasPrefix(raw, `"`) {
		var text string
		if err := json.Unmarshal(data, &text); err != nil {
			return err
		}
		raw = strings.TrimSpace(text)
		if raw == "" {
			*v = 0
			return nil
		}
	}
	parsed, err := strconv.ParseInt(raw, 10, 64)
	if err != nil {
		return fmt.Errorf("invalid settlement user id %q", raw)
	}
	*v = settlementUserID(parsed)
	return nil
}

func settlementUserIDValues(items []settlementUserID) []int64 {
	out := make([]int64, 0, len(items))
	for _, item := range items {
		out = append(out, int64(item))
	}
	return out
}

type userDTO struct {
	UserID        string `json:"user_id"`
	DisplayUserID string `json:"display_user_id"`
	Username      string `json:"username"`
	Avatar        string `json:"avatar"`
}

type pendingDTO struct {
	UserID                      string  `json:"user_id"`
	User                        userDTO `json:"user"`
	AgencyOwnerUserID           string  `json:"agency_owner_user_id"`
	AgencyOwner                 userDTO `json:"agency_owner"`
	Role                        string  `json:"role"`
	CycleKey                    string  `json:"cycle_key"`
	RegionID                    int64   `json:"region_id"`
	RegionName                  string  `json:"region_name"`
	PolicyID                    uint64  `json:"policy_id"`
	PolicyVersion               uint64  `json:"policy_version"`
	PolicyName                  string  `json:"policy_name"`
	SettlementType              string  `json:"settlement_type"`
	TriggerMode                 string  `json:"trigger_mode"`
	LevelNo                     int32   `json:"level_no"`
	RequiredDiamonds            int64   `json:"required_diamonds"`
	TotalDiamonds               int64   `json:"total_diamonds"`
	HostSalaryUSDMinorTarget    int64   `json:"host_salary_usd_minor_target"`
	HostSalaryUSDTarget         string  `json:"host_salary_usd_target"`
	HostSalaryUSDMinorDelta     int64   `json:"host_salary_usd_minor_delta"`
	HostSalaryUSDDelta          string  `json:"host_salary_usd_delta"`
	HostCoinRewardTarget        int64   `json:"host_coin_reward_target"`
	HostCoinRewardDelta         int64   `json:"host_coin_reward_delta"`
	AgencySalaryUSDMinorTarget  int64   `json:"agency_salary_usd_minor_target"`
	AgencySalaryUSDTarget       string  `json:"agency_salary_usd_target"`
	AgencySalaryUSDMinorDelta   int64   `json:"agency_salary_usd_minor_delta"`
	AgencySalaryUSDDelta        string  `json:"agency_salary_usd_delta"`
	ResidualUSDMinorDelta       int64   `json:"residual_usd_minor_delta"`
	ResidualUSDDelta            string  `json:"residual_usd_delta"`
	TotalUSDMinorDelta          int64   `json:"total_usd_minor_delta"`
	TotalUSDDelta               string  `json:"total_usd_delta"`
	SettledLevelNo              int32   `json:"settled_level_no"`
	SettledHostSalaryUSDMinor   int64   `json:"settled_host_salary_usd_minor"`
	SettledHostSalaryUSD        string  `json:"settled_host_salary_usd"`
	SettledHostCoinReward       int64   `json:"settled_host_coin_reward"`
	SettledAgencySalaryUSDMinor int64   `json:"settled_agency_salary_usd_minor"`
	SettledAgencySalaryUSD      string  `json:"settled_agency_salary_usd"`
	LastSettledTotalDiamonds    int64   `json:"last_settled_total_diamonds"`
	ResidualUSDMinor            int64   `json:"residual_usd_minor"`
	ResidualUSD                 string  `json:"residual_usd"`
	MonthEndClearedAtMS         int64   `json:"month_end_cleared_at_ms"`
	Status                      string  `json:"status"`
}

type settlementDTO struct {
	SettlementID              string  `json:"settlement_id"`
	CommandID                 string  `json:"command_id"`
	TransactionID             string  `json:"transaction_id"`
	SettlementType            string  `json:"settlement_type"`
	TriggerMode               string  `json:"trigger_mode"`
	SettlementRole            string  `json:"settlement_role"`
	UserID                    string  `json:"user_id"`
	User                      userDTO `json:"user"`
	AgencyOwnerUserID         string  `json:"agency_owner_user_id"`
	AgencyOwner               userDTO `json:"agency_owner"`
	CycleKey                  string  `json:"cycle_key"`
	PolicyID                  uint64  `json:"policy_id"`
	PolicyVersion             uint64  `json:"policy_version"`
	LevelNo                   int32   `json:"level_no"`
	TotalDiamonds             int64   `json:"total_diamonds"`
	HostSalaryUSDMinorDelta   int64   `json:"host_salary_usd_minor_delta"`
	HostSalaryUSDDelta        string  `json:"host_salary_usd_delta"`
	HostCoinRewardDelta       int64   `json:"host_coin_reward_delta"`
	AgencySalaryUSDMinorDelta int64   `json:"agency_salary_usd_minor_delta"`
	AgencySalaryUSDDelta      string  `json:"agency_salary_usd_delta"`
	ResidualUSDMinorDelta     int64   `json:"residual_usd_minor_delta"`
	ResidualUSDDelta          string  `json:"residual_usd_delta"`
	Status                    string  `json:"status"`
	Reason                    string  `json:"reason"`
	CreatedAtMS               int64   `json:"created_at_ms"`
}

type query struct {
	Page              int
	PageSize          int
	CycleKey          string
	SettlementType    string
	Status            string
	UserID            int64
	UserFilter        shared.UserIdentityFilter
	AgencyOwnerUserID int64
	AgencyOwnerFilter shared.UserIdentityFilter
	PolicyID          uint64
	StartAtMS         int64
	EndAtMS           int64
}

type pendingQuery struct {
	Page           int
	PageSize       int
	Role           string
	CycleKey       string
	SettlementType string
	TriggerMode    string
	RegionID       int64
	CountryID      int64
	CountryCode    string
	UserID         int64
}

type settleRequest struct {
	Role           string             `json:"role"`
	CycleKey       string             `json:"cycle_key"`
	SettlementType string             `json:"settlement_type"`
	TriggerMode    string             `json:"trigger_mode"`
	RegionID       int64              `json:"region_id"`
	CountryID      int64              `json:"country_id"`
	CountryCode    string             `json:"country_code"`
	UserIDs        []settlementUserID `json:"user_ids"`
}

type settleResultDTO struct {
	Role           string          `json:"role"`
	CycleKey       string          `json:"cycle_key"`
	SettlementType string          `json:"settlement_type"`
	TriggerMode    string          `json:"trigger_mode"`
	RequestedCount int             `json:"requested_count"`
	ProcessedCount int             `json:"processed_count"`
	SuccessCount   int             `json:"success_count"`
	SkippedCount   int             `json:"skipped_count"`
	FailureCount   int             `json:"failure_count"`
	Records        []settlementDTO `json:"records"`
}
