<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Business\Purchase;

use App\Business\Purchase\Enums\PurchaseOrderReceiptStatus;
use App\Business\Purchase\Enums\PurchaseOrderStatus;
use App\Models\DberpPurchaseOrder;
use App\Support\DberpNumberFormatter;
use App\Tools\Entity\EntityReference;
use App\Tools\Entity\EntityType;
use App\Tools\Support\ToolAmountRange;
use App\Tools\Support\ToolDateRange;
use App\Tools\Support\ToolPagedQuery;
use Illuminate\Database\Eloquent\Builder;

/**
 * 采购订单只读列表。不复用 Filament Resource 表格查询，避免把 UI 筛选扩成公开 Tool API。
 */
final class PurchaseOrderSearchQuery
{
    public const SORTABLE = ['id', 'code', 'business_time', 'total_amount', 'status'];

    public const DEFAULT_SORT = 'business_time';

    /**
     * @param  array<string, mixed>  $input
     * @return array{items: list<array<string, mixed>>, page: int, per_page: int, total: int}
     */
    public function search(array $input): array
    {
        $dates = ToolDateRange::parseOptional(
            $input['date_from'] ?? null,
            $input['date_until'] ?? null,
            'date_from',
            'date_until',
        );
        $amounts = ToolAmountRange::parseOptional(
            $input['amount_min'] ?? null,
            $input['amount_max'] ?? null,
            'amount_min',
            'amount_max',
        );

        $query = DberpPurchaseOrder::query()->with('supplier');
        $table = (new DberpPurchaseOrder)->getTable();

        $keyword = trim((string) ($input['q'] ?? ''));
        if ($keyword !== '') {
            $like = '%'.$keyword.'%';
            $query->where(function (Builder $builder) use ($like, $table): void {
                $builder
                    ->where($table.'.code', 'like', $like)
                    ->orWhereHas('supplier', function (Builder $supplier) use ($like): void {
                        $supplier
                            ->where('code', 'like', $like)
                            ->orWhere('name', 'like', $like);
                    });
            });
        }

        if (($input['supplier_id'] ?? 0) > 0) {
            $query->where($table.'.supplier_id', (int) $input['supplier_id']);
        }

        $status = trim((string) ($input['status'] ?? ''));
        if ($status !== '') {
            $query->where($table.'.status', $status);
        }

        $receipt = PurchaseOrderReceiptStatus::tryFrom(trim((string) ($input['receipt_status'] ?? '')));
        if ($receipt instanceof PurchaseOrderReceiptStatus) {
            $query->whereIn($table.'.status', $receipt->statusValues());
        }

        if ($dates['from'] !== null) {
            $query->whereDate($table.'.business_time', '>=', $dates['from']);
        }

        if ($dates['until'] !== null) {
            $query->whereDate($table.'.business_time', '<=', $dates['until']);
        }

        if ($amounts['min'] !== null) {
            $query->where($table.'.total_amount', '>=', $amounts['min']);
        }

        if ($amounts['max'] !== null) {
            $query->where($table.'.total_amount', '<=', $amounts['max']);
        }

        $page = ToolPagedQuery::paginate(
            $query,
            $input,
            self::SORTABLE,
            self::DEFAULT_SORT,
        );

        return [
            'items' => $page['rows']
                ->map(fn (mixed $order): array => $this->mapSummary($order))
                ->values()
                ->all(),
            ...ToolPagedQuery::meta($page),
        ];
    }

    /**
     * @return list<string>
     */
    public static function statusValues(): array
    {
        return array_map(
            static fn (PurchaseOrderStatus $status): string => $status->value,
            PurchaseOrderStatus::cases(),
        );
    }

    /**
     * @return array<string, mixed>
     */
    private function mapSummary(mixed $order): array
    {
        if (! $order instanceof DberpPurchaseOrder) {
            return [];
        }

        $supplier = $order->supplier;
        $receipt = PurchaseOrderReceiptStatus::fromOrderStatus((string) $order->status);

        $supplierPayload = [
            'id' => $supplier === null ? null : (int) $supplier->getKey(),
            'code' => $this->nullableString($supplier?->code),
            'name' => (string) ($supplier?->name ?? ''),
        ];

        return EntityReference::attach([
            'id' => (int) $order->getKey(),
            'code' => (string) $order->code,
            'status' => (string) $order->status,
            'receipt_status' => $receipt?->value,
            'business_time' => $order->business_time?->toIso8601String(),
            'expected_arrival_date' => $order->expected_arrival_date?->toDateString(),
            'supplier' => EntityReference::attachNested($supplierPayload, EntityType::Supplier),
            'amounts' => [
                'total_quantity' => DberpNumberFormatter::quantity($order->total_quantity),
                'total_amount' => DberpNumberFormatter::money($order->total_amount),
                'remaining_arrival_quantity' => DberpNumberFormatter::quantity($order->remaining_arrival_quantity),
            ],
        ], EntityType::PurchaseOrder, (int) $order->getKey(), (string) $order->code);
    }

    private function nullableString(mixed $value): ?string
    {
        if ($value === null) {
            return null;
        }

        $normalized = trim((string) $value);

        return $normalized === '' ? null : $normalized;
    }
}
