<?php

namespace App\Modules\Procurement\Services;

use App\Modules\Operations\Services\OperationalSignalRecorder;
use App\Modules\Procurement\Exceptions\ReceivingOperationalException;
use App\Modules\Procurement\Models\GoodsReceipt;

final class ProcurementOperationalUiFailureRecorder
{
    public function __construct(
        private readonly OperationalSignalRecorder $recorder,
    ) {}

    public function recordDraftCreationFailure(
        int $tenantId,
        int $purchaseOrderId,
        ReceivingOperationalException $exception,
    ): void {
        $this->recorder->record(
            $tenantId,
            'procurement',
            'receipt_operational_block',
            'warning',
            $exception->violationCode,
            $exception->getMessage(),
            null,
            'purchase_order',
            $purchaseOrderId,
            ['phase' => 'draft_create'],
        );
    }

    public function recordFromReceivingException(
        int $tenantId,
        GoodsReceipt $receipt,
        ReceivingOperationalException $exception,
        string $phase,
    ): void {
        $sev = match ($exception->violationCode) {
            'over_receive', 'cross_po', 'line_quarantined' => 'warning',
            'receipt_not_found', 'po_not_found' => 'error',
            default => 'warning',
        };

        $this->recorder->record(
            $tenantId,
            'procurement',
            $phase === 'post' ? 'receipt_posting_failure' : 'receipt_validation_failure',
            $sev,
            $exception->violationCode,
            $exception->getMessage(),
            $receipt->correlation_id,
            'goods_receipt',
            (int) $receipt->id,
            [
                'phase' => $phase,
                'purchase_order_id' => $receipt->purchase_order_id,
            ],
        );
    }
}
