<?php

declare(strict_types=1);

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

namespace App\Business\Inventory;

use App\Business\Inventory\Enums\InventoryBalanceStockStatus;
use App\Models\DberpInventoryBalance;
use App\Support\DberpNumberFormatter;
use App\Tools\Entity\EntityReference;
use App\Tools\Entity\EntityType;
use App\Tools\Support\ToolAmountRange;
use App\Tools\Support\ToolPagedQuery;
use Illuminate\Database\Eloquent\Builder;

/**
 * 库存余额只读检索。按关键词与数量条件查余额行，不复用 inventory.get 的流水汇总，也不走预警服务。
 */
final class InventoryBalanceSearchQuery
{
    public const SORTABLE = ['id', 'product_id', 'warehouse_id', 'realtime_quantity', 'available_quantity', 'last_moved_at'];

    public const DEFAULT_SORT = 'last_moved_at';

    /**
     * @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
    {
        $quantities = ToolAmountRange::parseOptional(
            $input['quantity_min'] ?? null,
            $input['quantity_max'] ?? null,
            'quantity_min',
            'quantity_max',
        );

        $query = DberpInventoryBalance::query()->with(['product.category', 'warehouse', 'productSku']);
        $table = (new DberpInventoryBalance)->getTable();

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

        foreach (['product_id', 'product_sku_id', 'warehouse_id'] as $key) {
            if (($input[$key] ?? 0) > 0) {
                $query->where($table.'.'.$key, (int) $input[$key]);
            }
        }

        if (($input['category_id'] ?? 0) > 0) {
            $query->whereHas('product', function (Builder $product) use ($input): void {
                $product->where('category_id', (int) $input['category_id']);
            });
        }

        $stockStatus = InventoryBalanceStockStatus::tryFrom(trim((string) ($input['stock_status'] ?? '')));
        if ($stockStatus instanceof InventoryBalanceStockStatus) {
            match ($stockStatus) {
                InventoryBalanceStockStatus::InStock => $query->where($table.'.realtime_quantity', '>', 0),
                InventoryBalanceStockStatus::Zero => $query->zeroStock(),
                InventoryBalanceStockStatus::Low => $query->lowStock(),
            };
        }

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

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

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

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

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

        $product = $row->product;
        $warehouse = $row->warehouse;
        $sku = $row->productSku;

        $payload = [
            'id' => (int) $row->getKey(),
            'product_id' => (int) $row->product_id,
            'product_code' => (string) ($product?->code ?? ''),
            'product_name' => (string) ($product?->name ?? ''),
            'product_sku_id' => $row->product_sku_id === null ? null : (int) $row->product_sku_id,
            'sku_code' => $this->nullableString($sku?->sku_code),
            'spec_text' => $this->nullableString($sku?->spec_text),
            'warehouse_id' => (int) $row->warehouse_id,
            'warehouse_code' => $this->nullableString($warehouse?->code),
            'warehouse_name' => (string) ($warehouse?->name ?? ''),
            'category_id' => $product?->category_id === null ? null : (int) $product->category_id,
            'category_name' => $this->nullableString($product?->category?->name),
            'realtime_quantity' => DberpNumberFormatter::quantity($row->realtime_quantity),
            'available_quantity' => DberpNumberFormatter::quantity($row->available_quantity),
            'occupied_quantity' => DberpNumberFormatter::quantity($row->occupied_quantity),
            'safety_stock' => DberpNumberFormatter::quantity($row->safety_stock),
            'last_moved_at' => $row->last_moved_at?->toIso8601String(),
        ];

        $refs = array_values(array_filter([
            EntityReference::tryMake(EntityType::Product, $row->product_id, $product?->code, $product?->name),
            EntityReference::tryMake(EntityType::Warehouse, $row->warehouse_id, $warehouse?->code, $warehouse?->name),
        ]));

        return EntityReference::attachMany($payload, ...$refs);
    }

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

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

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