<?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\DberpCustomer;
use App\Tools\Entity\EntityReference;
use App\Tools\Entity\EntityType;
use App\Tools\Support\ToolPagedQuery;
use Illuminate\Database\Eloquent\Builder;

/**
 * 客户只读检索。仅搜索已批准业务字段，不暴露手机号、额度、备注等内部/个人字段。
 */
final class CustomerSearchQuery
{
    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 = DberpCustomer::query()->with(['customerCategory', 'salesperson']);

        $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['customer_category_id'] ?? 0) > 0) {
            $query->where('customer_category_id', (int) $input['customer_category_id']);
        }

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

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

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

        return EntityReference::attach([
            'id' => (int) $customer->getKey(),
            'code' => (string) $customer->code,
            'name' => (string) $customer->name,
            'is_enabled' => (bool) $customer->is_enabled,
            'customer_category_id' => $customer->customer_category_id === null ? null : (int) $customer->customer_category_id,
            'customer_category_name' => $this->nullableString($customer->customerCategory?->name),
            'settlement_method' => $this->nullableString($customer->settlement_method),
            'salesperson_employee_id' => $customer->salesperson_employee_id === null ? null : (int) $customer->salesperson_employee_id,
            'salesperson_name' => $this->nullableString($customer->salesperson?->name),
            'contact_person' => $this->nullableString($customer->contact_person),
            'sort_order' => (int) ($customer->sort_order ?? 0),
        ], EntityType::Customer, (int) $customer->getKey(), (string) $customer->code, (string) $customer->name);
    }

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

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

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