<?php

namespace App\Services\Esign;

use App\Enum\Esign\EsignEventType;
use App\Enum\Esign\EsignStatus;

/**
 * Maps a Fintrixor webhook event name (from the `event` field / X-Esign-Event
 * header) onto our canonical EsignEventType + EsignStatus pair, plus the
 * EsignDocument timestamp column to stamp (if any).
 *
 * @phpstan-type EsignMapping array{event: EsignEventType, status: ?EsignStatus, timestamp_column: ?string}
 */
class EsignEventMapper
{
    /**
     * @return array{event: EsignEventType, status: ?EsignStatus, timestamp_column: ?string}
     */
    public function map(string $eventName): array
    {
        return match (strtolower(trim($eventName))) {
            'document.created'
                // We create documents with auto_send, so they are already SENT
                // our side; record the event but don't regress status.
                => ['event' => EsignEventType::CREATED, 'status' => null, 'timestamp_column' => null],
            'document.sent'
                => ['event' => EsignEventType::SENT, 'status' => EsignStatus::SENT, 'timestamp_column' => 'sent_at'],
            'document.viewed'
                => ['event' => EsignEventType::VIEWED, 'status' => EsignStatus::VIEWED, 'timestamp_column' => 'viewed_at'],
            'document.signed'
                => ['event' => EsignEventType::SIGNED, 'status' => EsignStatus::SIGNED, 'timestamp_column' => 'signed_at'],
            'document.completed'
                => ['event' => EsignEventType::COMPLETED, 'status' => EsignStatus::COMPLETED, 'timestamp_column' => 'completed_at'],
            'certificate.generated'
                => ['event' => EsignEventType::CERTIFICATE_GENERATED, 'status' => null, 'timestamp_column' => null],
            default
                => ['event' => EsignEventType::UNKNOWN, 'status' => null, 'timestamp_column' => null],
        };
    }
}
