<?php

declare(strict_types=1);

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

namespace App\Tools\Purchase;

use App\Business\Purchase\Enums\PurchaseOrderReceiptStatus;
use App\Business\Purchase\PurchaseOrderSearchQuery;
use App\Services\DberpPermissionService;
use App\Tools\Contracts\Tool;
use App\Tools\Entity\EntityReferenceSchema;
use App\Tools\Enums\ToolRisk;
use App\Tools\Support\ToolCurrency;
use App\Tools\Support\ToolDateSchema;
use App\Tools\Support\ToolListSchema;
use App\Tools\ToolExecutionContext;
use App\Tools\ToolMetadata;
use App\Tools\ToolPermission;

final class PurchaseOrderSearchTool implements Tool
{
    public function __construct(
        private readonly PurchaseOrderSearchQuery $query,
    ) {}

    public function metadata(): ToolMetadata
    {
        $itemSchema = [
            'type' => 'object',
            'required' => [
                'id',
                'code',
                'status',
                'supplier',
                'amounts',
            ],
            'additionalProperties' => false,
            'properties' => [
                'id' => ['type' => 'integer'],
                'code' => ['type' => 'string'],
                'status' => ['type' => 'string'],
                'receipt_status' => ['type' => 'string'],
                'business_time' => ['type' => 'string'],
                'expected_arrival_date' => ['type' => 'string'],
                'supplier' => EntityReferenceSchema::nestedCounterparty(),
                'amounts' => [
                    'type' => 'object',
                    'required' => [
                        'total_quantity',
                        'total_amount',
                        'remaining_arrival_quantity',
                    ],
                    'additionalProperties' => false,
                    'properties' => [
                        'total_quantity' => ['type' => 'string'],
                        'total_amount' => ['type' => 'string'],
                        'remaining_arrival_quantity' => ['type' => 'string'],
                    ],
                ],
            ],
        ];

        return new ToolMetadata(
            name: 'purchase.order.search',
            version: 1,
            description: '按编号、供应商、状态、收货进度、日期与金额检索采购订单列表（只读，分页）。',
            permission: ToolPermission::permission(DberpPermissionService::VIEW_PURCHASE_ORDER),
            risk: ToolRisk::ReadOnly,
            inputSchema: [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => [
                    'q' => [
                        'type' => 'string',
                        'minLength' => 1,
                        'maxLength' => 100,
                    ],
                    'supplier_id' => [
                        'type' => 'integer',
                        'minimum' => 1,
                    ],
                    'status' => [
                        'type' => 'string',
                        'enum' => PurchaseOrderSearchQuery::statusValues(),
                    ],
                    'receipt_status' => [
                        'type' => 'string',
                        'enum' => PurchaseOrderReceiptStatus::values(),
                    ],
                    'date_from' => ToolDateSchema::dateProperty('Inclusive business calendar date Y-m-d.'),
                    'date_until' => ToolDateSchema::dateProperty('Inclusive business calendar date Y-m-d.'),
                    'period_preset' => ToolDateSchema::periodPresetProperty(),
                    'amount_min' => [
                        'type' => 'number',
                        'minimum' => 0,
                    ],
                    'amount_max' => [
                        'type' => 'number',
                        'minimum' => 0,
                    ],
                    ...ToolListSchema::paginationInputProperties(
                        PurchaseOrderSearchQuery::SORTABLE,
                        PurchaseOrderSearchQuery::DEFAULT_SORT,
                    ),
                ],
            ],
            outputSchema: ToolListSchema::paginatedOutputSchemaWithCurrency(EntityReferenceSchema::withRef($itemSchema)),
            owner: 'core',
        );
    }

    /**
     * @param  array<string, mixed>  $input
     * @return array<string, mixed>
     */
    public function execute(ToolExecutionContext $context, array $input): array
    {
        return [
            ...$this->query->search($input),
            'currency' => ToolCurrency::metadata($context),
        ];
    }
}
