<?php

namespace App\Http\Controllers;

use App\Jobs\ForwardWebhookJob;
use App\Models\WebhookEvent;
use App\Services\PayloadParser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WebhookController extends Controller
{
    public function singapay(Request $request)
    {
        return $this->receive('singapay', $request);
    }

    public function faspay(Request $request)
    {
        return $this->receive('faspay', $request);
    }

    private function receive(string $provider, Request $request)
    {
        $payload = $request->all();
        $headers = collect($request->headers->all())
            ->map(fn ($v) => is_array($v) && count($v) === 1 ? $v[0] : $v)
            ->toArray();

        $reffNo = PayloadParser::extractReffNo($provider, $payload);
        $prefix = PayloadParser::parsePrefix($reffNo);

        $event = WebhookEvent::create([
            'provider' => $provider,
            'reff_no' => $reffNo,
            'prefix' => $prefix,
            'status' => WebhookEvent::STATUS_PENDING,
            'request_payload' => $payload,
            'request_headers' => $headers,
        ]);

        Log::info('Webhook received', [
            'event_id' => $event->id,
            'provider' => $provider,
            'reff_no' => $reffNo,
            'prefix' => $prefix,
        ]);

        ForwardWebhookJob::dispatch($event->id);

        return response()->json([
            'status' => 'received',
            'event_id' => $event->id,
            'reff_no' => $reffNo,
        ], 200);
    }
}
