<?php

declare(strict_types=1);

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

namespace App\Business\Product;

use App\Models\DberpProduct;
use App\Support\DberpNumberFormatter;
use App\Tools\Entity\EntityReference;
use App\Tools\Entity\EntityType;
use App\Tools\Support\ToolPagedQuery;
use Illuminate\Database\Eloquent\Builder;

/**
 * 商品只读检索。不复用 Filament Resource 表格查询，避免把 UI 检索字段扩成公开 Tool API。
 */
final class ProductSearchQuery
{
    public const SORTABLE = ['id', 'code', 'name', 'sort_order', 'created_at'];

    public const DEFAULT_SORT = 'id';

    /**
     * @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
    {
        $query = DberpProduct::query()->with(['category', 'unit', 'brand']);

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

        $this->applyOptionalBoolean($query, $input, 'is_enabled');
        $this->applyOptionalBoolean($query, $input, 'can_sale');
        $this->applyOptionalBoolean($query, $input, 'can_purchase');

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

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

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

    /**
     * @param  array<string, mixed>  $input
     */
    private function applyOptionalBoolean(Builder $query, array $input, string $key): void
    {
        if (! array_key_exists($key, $input) || $input[$key] === null) {
            return;
        }

        $query->where($key, (bool) $input[$key]);
    }

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

        $brandName = $product->brand?->name;
        if ($brandName === null || trim((string) $brandName) === '') {
            $legacy = trim((string) ($product->brand_name ?? ''));
            $brandName = $legacy !== '' ? $legacy : null;
        }

        return EntityReference::attach([
            'id' => (int) $product->getKey(),
            'code' => (string) $product->code,
            'name' => (string) $product->name,
            'barcode' => $this->nullableString($product->barcode),
            'mnemonic_code' => $this->nullableString($product->mnemonic_code),
            'category_id' => $product->category_id === null ? null : (int) $product->category_id,
            'category_name' => $this->nullableString($product->category?->name),
            'brand_name' => $this->nullableString($brandName),
            'spec_model' => $this->nullableString($product->spec_model),
            'unit_id' => (int) $product->unit_id,
            'unit_name' => $this->nullableString($product->unit?->name),
            'is_enabled' => (bool) $product->is_enabled,
            'can_sale' => (bool) $product->can_sale,
            'can_purchase' => (bool) $product->can_purchase,
            'sales_price' => DberpNumberFormatter::price($product->sales_price),
        ], EntityType::Product, (int) $product->getKey(), (string) $product->code, (string) $product->name);
    }

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

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

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