<?php

namespace App\Http\Controllers;

use App\Actions\Esign\IngestEsignEventAction;
use App\Models\EsignDocument;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * Receives Fintrixor eSign webhooks (document.created/sent/viewed/signed/completed,
 * certificate.generated). Each event POSTs one JSON body
 * `{id, event, created_at, data:{document:{id, …}}}`.
 *
 * Correlates by the Fintrixor document id (data.document.id) → our EsignDocument.
 * Unauthenticated / no signature verification (per decision); tenant is resolved
 * from the matched document, never from HTTP context.
 */
class EsignWebhookController extends Controller
{
    public function input(Request $request, IngestEsignEventAction $ingest): JsonResponse
    {
        $payload    = $request->all();
        $eventName  = (string) ($payload['event'] ?? $request->header('X-Esign-Event', ''));
        $documentId = data_get($payload, 'data.document.id');
        $deliveryId = $request->header('X-Esign-Delivery') ?? ($payload['id'] ?? null);

        Log::debug('eSign webhook received', ['event' => $eventName, 'document_id' => $documentId]);

        // Malformed (no document id) → 200 so the provider doesn't retry forever.
        if (!$documentId) {
            Log::info('eSign webhook missing document id', ['payload' => $payload]);
            return response()->json(['status' => 'ignored'], 200);
        }

        $document = EsignDocument::withoutGlobalScopes()
            ->where('provider_document_id', $documentId)
            ->first();

        // Unknown document → visible 404.
        if (!$document) {
            Log::info('eSign webhook unmatched document', ['document_id' => $documentId]);
            return response()->json(['error' => 'not_found'], 404);
        }

        $ingest->handle($document, $eventName, $payload, $deliveryId);

        return response()->json(['status' => 'ok'], 200);
    }
}
