<?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\PurchaseOrderStatus;
use App\Business\Report\PurchaseAnalysisReportService;
use App\Tools\Contracts\Tool;
use App\Tools\Enums\ToolRisk;
use App\Tools\Support\ToolCurrency;
use App\Tools\Support\ToolDateRange;
use App\Tools\Support\ToolDateSchema;
use App\Tools\ToolExecutionContext;
use App\Tools\ToolMetadata;
use App\Tools\ToolPermission;

/**
 * 采购分析汇总。逾期到货沿用 Report Service 的 now()->toDateString() 口径，本步不按 Tool timezone 改写业务日期。
 */
final class PurchaseSummaryTool implements Tool
{
    public function __construct(
        private readonly PurchaseAnalysisReportService $purchaseAnalysisReportService,
    ) {}

    public function metadata(): ToolMetadata
    {
        $statusValues = PurchaseOrderStatus::statisticsScopeValues();

        return new ToolMetadata(
            name: 'purchase.summary',
            version: 1,
            description: '采购分析汇总（只读），指标口径与现有采购分析报表一致。',
            permission: ToolPermission::report('purchase-analysis'),
            risk: ToolRisk::ReadOnly,
            inputSchema: [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => [
                    'supplier_id' => ['type' => 'integer', 'minimum' => 1],
                    'handler_employee_id' => ['type' => 'integer', 'minimum' => 1],
                    'category_id' => ['type' => 'integer', 'minimum' => 1],
                    'product_id' => ['type' => 'integer', 'minimum' => 1],
                    'status' => [
                        'type' => 'string',
                        'enum' => $statusValues,
                    ],
                    'business_time_from' => ToolDateSchema::dateProperty('Inclusive business calendar date Y-m-d.'),
                    'business_time_until' => ToolDateSchema::dateProperty('Inclusive business calendar date Y-m-d.'),
                    'period_preset' => ToolDateSchema::periodPresetProperty(),
                ],
            ],
            outputSchema: [
                'type' => 'object',
                'required' => [
                    'order_count',
                    'total_amount',
                    'paid_amount',
                    'unpaid_amount',
                    'total_quantity',
                    'arrived_quantity',
                    'remaining_arrival_quantity',
                    'overdue_arrival_order_count',
                    'partial_received_order_count',
                    'fully_received_order_count',
                    'exception_count',
                    'return_order_count',
                    'currency',
                ],
                'additionalProperties' => false,
                'properties' => [
                    'order_count' => ['type' => 'integer'],
                    'total_amount' => ['type' => 'string'],
                    'paid_amount' => ['type' => 'string'],
                    'unpaid_amount' => ['type' => 'string'],
                    'total_quantity' => ['type' => 'string'],
                    'arrived_quantity' => ['type' => 'string'],
                    'remaining_arrival_quantity' => ['type' => 'string'],
                    'overdue_arrival_order_count' => ['type' => 'integer'],
                    'partial_received_order_count' => ['type' => 'integer'],
                    'fully_received_order_count' => ['type' => 'integer'],
                    'exception_count' => ['type' => 'integer'],
                    'return_order_count' => ['type' => 'integer'],
                    'currency' => ToolCurrency::outputSchema(),
                ],
            ],
            owner: 'core',
        );
    }

    /**
     * @param  array<string, mixed>  $input
     * @return array<string, mixed>
     */
    public function execute(ToolExecutionContext $context, array $input): array
    {
        ToolDateRange::parseOptional(
            $input['business_time_from'] ?? null,
            $input['business_time_until'] ?? null,
            'business_time_from',
            'business_time_until',
        );

        $summary = $this->purchaseAnalysisReportService->summary(
            $this->purchaseAnalysisReportService->normalizeFilters($input),
        );

        return [
            'order_count' => (int) $summary['order_count'],
            'total_amount' => (string) $summary['total_amount'],
            'paid_amount' => (string) $summary['paid_amount'],
            'unpaid_amount' => (string) $summary['unpaid_amount'],
            'total_quantity' => (string) $summary['total_quantity'],
            'arrived_quantity' => (string) $summary['arrived_quantity'],
            'remaining_arrival_quantity' => (string) $summary['remaining_arrival_quantity'],
            'overdue_arrival_order_count' => (int) $summary['overdue_arrival_order_count'],
            'partial_received_order_count' => (int) $summary['partial_received_order_count'],
            'fully_received_order_count' => (int) $summary['fully_received_order_count'],
            'exception_count' => (int) $summary['exception_count'],
            'return_order_count' => (int) $summary['return_order_count'],
            'currency' => ToolCurrency::metadata($context),
        ];
    }
}
