<?php

namespace App\Http\Controllers\Webhooks\Communications;

use App\Actions\Communications\IngestProviderEventAction;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SendGridEventController extends Controller
{
    public function __invoke(Request $request, IngestProviderEventAction $ingest): JsonResponse
    {
        $events = $request->json()->all();
        if (!is_array($events) || empty($events)) {
            return response()->json(['status' => 'empty'], 200);
        }

        $processed = 0;
        $skipped = 0;
        foreach ($events as $event) {
            if (!is_array($event)) {
                $skipped++;
                continue;
            }
            $result = $ingest->handleSendGrid($event);
            $result ? $processed++ : $skipped++;
        }

        return response()->json(['processed' => $processed, 'skipped' => $skipped], 200);
    }
}
