<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\WebhookEvent;
use App\Services\Billing\PaypalWebhookProcessor;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PaypalWebhookController extends Controller
{
    public function __construct(private readonly PaypalWebhookProcessor $processor) {}

    public function handle(Request $request): JsonResponse
    {
        $payload = $request->all();
        $eventType = (string) ($payload['event_type'] ?? '');
        $eventId = (string) ($payload['id'] ?? '');

        $signatureOk = $this->verifySignature($request);

        if ($eventId !== '' && WebhookEvent::where('provider', 'paypal')->where('event_id', $eventId)->exists()) {
            return response()->json(['ok' => true, 'duplicate' => true]);
        }

        $event = WebhookEvent::create([
            'provider' => 'paypal',
            'event_id' => $eventId !== '' ? $eventId : null,
            'event_type' => $eventType !== '' ? $eventType : null,
            'status' => $signatureOk ? 'received' : 'error',
            'payload' => $payload,
            'headers' => $this->extractHeaders($request),
            'received_at' => now(),
            'error' => $signatureOk ? null : 'signature_unverified',
        ]);

        if (! $signatureOk) {
            return response()->json(['ok' => true, 'signature' => 'unverified']);
        }

        try {
            $this->processor->process($eventType, $payload);
            $event->update([
                'status' => 'processed',
                'processed_at' => now(),
            ]);
        } catch (\Throwable $e) {
            $event->update([
                'status' => 'error',
                'error' => $e->getMessage(),
                'processed_at' => now(),
            ]);
        }

        return response()->json(['ok' => true]);
    }

    private function verifySignature(Request $request): bool
    {
        // TODO: Implement PayPal signature verification using transmission headers + webhook ID.
        // For now this returns true to allow local testing.
        return true;
    }

    /**
     * @return array<string,string>
     */
    private function extractHeaders(Request $request): array
    {
        $headers = [
            'paypal-transmission-id' => (string) $request->header('PayPal-Transmission-Id', ''),
            'paypal-transmission-sig' => (string) $request->header('PayPal-Transmission-Sig', ''),
            'paypal-cert-url' => (string) $request->header('PayPal-Cert-Url', ''),
            'paypal-auth-algo' => (string) $request->header('PayPal-Auth-Algo', ''),
            'paypal-transmission-time' => (string) $request->header('PayPal-Transmission-Time', ''),
        ];

        return array_filter($headers, fn (string $value): bool => $value !== '');
    }
}
