<?php

declare(strict_types=1);

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

namespace App\Business\Sales;

use App\Business\Sales\Enums\SalesOrderFulfillmentStatus;
use App\Business\Sales\Enums\SalesOrderStatus;
use App\Models\DberpSalesOrder;
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 SalesOrderSearchQuery
{
    public const SORTABLE = ['id', 'code', 'business_time', 'final_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 = DberpSalesOrder::query()->with('customer');
        $table = (new DberpSalesOrder)->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('customer', function (Builder $customer) use ($like): void {
                        $customer
                            ->where('code', 'like', $like)
                            ->orWhere('name', 'like', $like);
                    });
            });
        }

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

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

        $fulfillment = SalesOrderFulfillmentStatus::tryFrom(trim((string) ($input['fulfillment_status'] ?? '')));
        if ($fulfillment instanceof SalesOrderFulfillmentStatus) {
            $query->whereIn($table.'.status', $fulfillment->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.'.final_amount', '>=', $amounts['min']);
        }

        if ($amounts['max'] !== null) {
            $query->where($table.'.final_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 (SalesOrderStatus $status): string => $status->value,
            SalesOrderStatus::cases(),
        );
    }

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

        $customer = $order->customer;
        $fulfillment = SalesOrderFulfillmentStatus::fromOrderStatus((string) $order->status);

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

        return EntityReference::attach([
            'id' => (int) $order->getKey(),
            'code' => (string) $order->code,
            'status' => (string) $order->status,
            'fulfillment_status' => $fulfillment?->value,
            'business_time' => $order->business_time?->toIso8601String(),
            'due_date' => $order->due_date?->toDateString(),
            'customer' => EntityReference::attachNested($customerPayload, EntityType::Customer),
            'amounts' => [
                'total_quantity' => DberpNumberFormatter::quantity($order->total_quantity),
                'final_amount' => DberpNumberFormatter::money($order->final_amount),
            ],
        ], EntityType::SalesOrder, (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;
    }
}
