<?php

namespace App\Modules\Operations\Services;

use App\Modules\Inventory\Stock\Services\InventoryStockRebuildService;

final class OperationalControlRebuildRunner
{
    public function __construct(
        private readonly InventoryStockRebuildService $rebuild,
        private readonly OperationalSignalRecorder $recorder,
    ) {}

    /**
     * @return array{rows: int, mismatched_before: bool}
     */
    public function rebuildAndAudit(int $tenantId, int $actorUserId): array
    {
        $result = $this->rebuild->rebuildTenant($tenantId);
        $this->recorder->record(
            $tenantId,
            'inventory',
            'operator_rebuild',
            'info',
            'projection_rebuild_executed',
            'Stock projections rebuilt from ledger.',
            null,
            null,
            null,
            [
                'rows' => $result['rows'],
                'mismatched_before' => $result['mismatched_before'],
                'actor_user_id' => $actorUserId,
            ],
        );

        return $result;
    }

    public function recordDriftCheck(int $tenantId, bool $drift, int $actorUserId): void
    {
        $this->recorder->record(
            $tenantId,
            'inventory',
            'reconciliation_check',
            $drift ? 'warning' : 'info',
            $drift ? 'projection_drift_detected' : 'projection_aligned',
            $drift ? 'Ledger vs projection mismatch detected.' : 'Ledger matches projections.',
            null,
            null,
            null,
            ['actor_user_id' => $actorUserId, 'drift' => $drift],
        );
    }
}
