<?php

declare(strict_types=1);

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

namespace App\Tools\Sales;

use App\Business\Report\SalesAnalysisReportService;
use App\Business\Sales\Enums\SalesOrderStatus;
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;

final class SalesSummaryTool implements Tool
{
    public function __construct(
        private readonly SalesAnalysisReportService $salesAnalysisReportService,
    ) {}

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

        return new ToolMetadata(
            name: 'sales.summary',
            version: 1,
            description: '销售分析汇总（只读），指标口径与现有销售分析报表一致。',
            permission: ToolPermission::report('sales-analysis'),
            risk: ToolRisk::ReadOnly,
            inputSchema: [
                'type' => 'object',
                'additionalProperties' => false,
                'properties' => [
                    'customer_id' => ['type' => 'integer', 'minimum' => 1],
                    'handler_employee_id' => ['type' => 'integer', 'minimum' => 1],
                    'category_id' => ['type' => 'integer', 'minimum' => 1],
                    'product_id' => ['type' => 'integer', 'minimum' => 1],
                    'product_sku_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',
                    'final_amount',
                    'receivable_amount',
                    'received_amount',
                    'unreceived_amount',
                    'total_quantity',
                    'confirmed_order_count',
                    'partial_shipped_order_count',
                    'fully_shipped_order_count',
                    'currency',
                ],
                'additionalProperties' => false,
                'properties' => [
                    'order_count' => ['type' => 'integer'],
                    'final_amount' => ['type' => 'string'],
                    'receivable_amount' => ['type' => 'string'],
                    'received_amount' => ['type' => 'string'],
                    'unreceived_amount' => ['type' => 'string'],
                    'total_quantity' => ['type' => 'string'],
                    'confirmed_order_count' => ['type' => 'integer'],
                    'partial_shipped_order_count' => ['type' => 'integer'],
                    'fully_shipped_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->salesAnalysisReportService->summary(
            $this->salesAnalysisReportService->normalizeFilters($input),
        );

        return [
            'order_count' => (int) $summary['order_count'],
            'final_amount' => (string) $summary['final_amount'],
            'receivable_amount' => (string) $summary['receivable_amount'],
            'received_amount' => (string) $summary['received_amount'],
            'unreceived_amount' => (string) $summary['unreceived_amount'],
            'total_quantity' => (string) $summary['total_quantity'],
            'confirmed_order_count' => (int) $summary['confirmed_order_count'],
            'partial_shipped_order_count' => (int) $summary['partial_shipped_order_count'],
            'fully_shipped_order_count' => (int) $summary['fully_shipped_order_count'],
            'currency' => ToolCurrency::metadata($context),
        ];
    }
}
