<?php

namespace App\Services\AgentSettlement;

/** 结算中心账务流水列表筛选。 */
final class SettlementLedgerListFilters
{
    public function __construct(
        public readonly ?int $settlementPeriodId = null,
        public readonly ?int $playerId = null,
        public readonly ?string $entryKind = null,
        public readonly ?string $txnNo = null,
        public readonly ?string $playerAccount = null,
        public readonly ?string $bizType = null,
        public readonly ?string $billStatus = null,
        public readonly bool $actionableOnly = false,
        public readonly ?string $createdFrom = null,
        public readonly ?string $createdTo = null,
        public readonly bool $badDebtOnly = false,
        public readonly bool $betFlowOnly = false,
        public readonly bool $betFlowDisplaySimple = false,
    ) {}

    public static function fromQuery(array $query): self
    {
        $playerId = (int) ($query['player_id'] ?? 0);

        return new self(
            settlementPeriodId: self::positiveInt($query['settlement_period_id'] ?? null),
            playerId: $playerId > 0 ? $playerId : null,
            entryKind: self::nonEmptyString($query['entry_kind'] ?? null),
            txnNo: self::nonEmptyString($query['txn_no'] ?? null),
            playerAccount: self::nonEmptyString($query['player_account'] ?? null),
            bizType: self::nonEmptyString($query['reason'] ?? $query['biz_type'] ?? null),
            billStatus: self::nonEmptyString($query['bill_status'] ?? null),
            actionableOnly: filter_var($query['actionable_only'] ?? false, FILTER_VALIDATE_BOOLEAN),
            createdFrom: self::nonEmptyString($query['created_from'] ?? null),
            createdTo: self::nonEmptyString($query['created_to'] ?? null),
            badDebtOnly: filter_var($query['bad_debt_only'] ?? false, FILTER_VALIDATE_BOOLEAN),
            betFlowOnly: filter_var($query['bet_flow_only'] ?? false, FILTER_VALIDATE_BOOLEAN),
            betFlowDisplaySimple: self::betFlowDisplaySimple($query),
        );
    }

    /**
     * @param  array<string, mixed>  $query
     */
    private static function betFlowDisplaySimple(array $query): bool
    {
        if (filter_var($query['bet_flow_only'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
            return true;
        }

        return trim((string) ($query['bet_flow_display'] ?? '')) === 'simple';
    }

    private static function positiveInt(mixed $value): ?int
    {
        $id = (int) $value;

        return $id > 0 ? $id : null;
    }

    private static function nonEmptyString(mixed $value): ?string
    {
        $s = trim((string) $value);

        return $s !== '' ? $s : null;
    }
}
