<?php

declare(strict_types=1);

namespace App\Services\Dashboard;

/**
 * Сверка заказа у поставщика для дашборда: спрос клиентов → надо по формуле
 * → заказали по факту → совпадает ли. Чистая логика (без БД), тестируема.
 *
 * Формула = SupplierQuotaAllocator::computeOrder = max(max(лимитов), ceil(сумма/3)).
 * Spec: docs/superpowers/specs/2026-06-27-admin-command-center-design.md
 */
class SupplyReconciliation
{
    /**
     * @param  list<array{signal_type:string,identifier:string,demand:int,max_limit:int}>  $demand
     * @param  array<string,int>  $orderedByKey  ключ "signal_type|identifier" => SUM(current_limit)
     * @return array{groups:list<array{signal_type:string,identifier:string,demand:int,formula:int,ordered:int,in_sync:bool}>,totals:array{demand:int,formula:int,ordered:int,mismatches:int}}
     */
    public static function build(array $demand, array $orderedByKey): array
    {
        $groups = [];
        $sumDemand = 0;
        $sumFormula = 0;
        $sumOrdered = 0;
        $mismatches = 0;

        foreach ($demand as $d) {
            $formula = max((int) $d['max_limit'], (int) ceil($d['demand'] / 3));
            $key = $d['signal_type'].'|'.$d['identifier'];
            $ordered = (int) ($orderedByKey[$key] ?? 0);
            $inSync = $formula === $ordered;

            $groups[] = [
                'signal_type' => (string) $d['signal_type'],
                'identifier' => (string) $d['identifier'],
                'demand' => (int) $d['demand'],
                'formula' => $formula,
                'ordered' => $ordered,
                'in_sync' => $inSync,
            ];

            $sumDemand += (int) $d['demand'];
            $sumFormula += $formula;
            $sumOrdered += $ordered;
            if (! $inSync) {
                $mismatches++;
            }
        }

        return [
            'groups' => $groups,
            'totals' => [
                'demand' => $sumDemand,
                'formula' => $sumFormula,
                'ordered' => $sumOrdered,
                'mismatches' => $mismatches,
            ],
        ];
    }
}
