<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Payment;

use App\Http\Controllers\Controller;
use App\Models\PaymentMethod;
use App\Models\PaymentWebhook;
use App\Services\Payment\PaymentRouter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class WebhookController extends Controller
{
    public function __construct(private readonly PaymentRouter $router)
    {
    }

    public function handle(Request $request, string $provider): JsonResponse
    {
        abort_unless(in_array($provider, PaymentMethod::PROVIDERS, true), Response::HTTP_NOT_FOUND);

        $payload = $request->all();
        $signature = $request->header('X-Signature') ?? $request->header('Toss-Signature') ?? $request->header('Stripe-Signature');

        $gw = $this->router->gatewayByName($provider);
        $ok = $gw->verifyWebhook(json_encode($payload), $signature, $request->headers->all());

        $webhook = PaymentWebhook::create([
            'tenant_id' => $request->header('X-Tenant-ID'),
            'provider' => $provider,
            'event_type' => $payload['event_type'] ?? ($payload['type'] ?? 'unknown'),
            'payload' => $payload,
            'signature' => $signature,
            'processed_at' => $ok ? now() : null,
        ]);

        if (! $ok) {
            return response()->json(['error' => 'INVALID_SIGNATURE'], Response::HTTP_BAD_REQUEST);
        }

        return response()->json(['data' => ['id' => $webhook->id, 'received' => true]]);
    }
}
