<?php

declare(strict_types=1);

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

namespace App\Business\MasterData;

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

/**
 * 供应商只读检索。仅搜索已批准业务字段，不暴露手机号、地址、备注等内部/个人字段。
 */
final class SupplierSearchQuery
{
    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 = DberpSupplier::query()->with(['supplierCategory']);

        $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);
            });
        }

        if (array_key_exists('is_enabled', $input) && $input['is_enabled'] !== null) {
            $query->where('is_enabled', (bool) $input['is_enabled']);
        }

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

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

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

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

        return EntityReference::attach([
            'id' => (int) $supplier->getKey(),
            'code' => (string) $supplier->code,
            'name' => (string) $supplier->name,
            'is_enabled' => (bool) $supplier->is_enabled,
            'supplier_category_id' => $supplier->supplier_category_id === null ? null : (int) $supplier->supplier_category_id,
            'supplier_category_name' => $this->nullableString($supplier->supplierCategory?->name),
            'settlement_method' => $this->nullableString($supplier->settlement_method),
            'contact_person' => $this->nullableString($supplier->contact_person),
            'sort_order' => (int) ($supplier->sort_order ?? 0),
        ], EntityType::Supplier, (int) $supplier->getKey(), (string) $supplier->code, (string) $supplier->name);
    }

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

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

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