<?php

namespace App\Http\Controllers\Api;

use App\Events\ServiceEventOccurred;
use App\Http\Controllers\Controller;
use App\Services\Events\ServiceEventSignature;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class ServiceEventController extends Controller
{
    public function __invoke(Request $request): JsonResponse
    {
        $secret = (string) config('service_events.inbound_secret');
        $signature = (string) $request->header('X-Ladill-Signature', '');

        if (! ServiceEventSignature::verify($request->getContent(), $signature, $secret)) {
            return response()->json(['error' => 'invalid signature'], 401);
        }

        $eventId = (string) $request->header('X-Ladill-Event-Id', (string) $request->input('id', ''));
        if ($eventId !== '') {
            if (Cache::has("svcevt:{$eventId}")) {
                return response()->json(['status' => 'duplicate']);
            }
            Cache::put("svcevt:{$eventId}", true, now()->addDay());
        }

        event(new ServiceEventOccurred((string) $request->input('event'), (array) $request->input('data', [])));

        return response()->json(['status' => 'accepted']);
    }
}
