<?php

namespace App\Services\AgentSettlement;

/** 结算中心收付与调账操作记录筛选。 */
final class SettlementOperationsListFilters
{
    public function __construct(
        public readonly ?int $settlementPeriodId = null,
        public readonly ?int $adminSiteId = null,
        public readonly ?int $billId = null,
        public readonly ?string $keyword = null,
        public readonly string $operationType = 'all',
    ) {}

    public static function fromQuery(array $query): self
    {
        $billId = (int) ($query['bill_id'] ?? 0);
        $operationType = trim((string) ($query['operation_type'] ?? 'all'));
        if (! in_array($operationType, ['all', 'payment', 'adjustment', 'reversal', 'bad_debt'], true)) {
            $operationType = 'all';
        }

        $periodId = (int) ($query['settlement_period_id'] ?? 0);
        $siteId = (int) ($query['admin_site_id'] ?? 0);

        return new self(
            settlementPeriodId: $periodId > 0 ? $periodId : null,
            adminSiteId: $siteId > 0 ? $siteId : null,
            billId: $billId > 0 ? $billId : null,
            keyword: self::nonEmptyString($query['keyword'] ?? null),
            operationType: $operationType,
        );
    }

    public function includesPayments(): bool
    {
        return in_array($this->operationType, ['all', 'payment'], true);
    }

    public function includesAdjustments(): bool
    {
        return in_array($this->operationType, ['all', 'adjustment', 'reversal', 'bad_debt'], true);
    }

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

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