<?php

namespace App\Http\Controllers\Webhooks;

use App\Http\Controllers\Controller;
use App\Jobs\SyncFromGoogleCalendarJob;
use App\Models\CalendarIntegration;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class GoogleCalendarWebhookController extends Controller
{
    /**
     * Google sendet hier einen POST sobald sich im Kalender etwas ändert.
     * Header X-Goog-Channel-Id identifiziert welche Integration betroffen ist.
     * Header X-Goog-Resource-State: "sync" (Test-Ping) | "exists" (Änderung)
     */
    public function __invoke(Request $request): Response
    {
        $channelId     = $request->header('X-Goog-Channel-Id');
        $resourceState = $request->header('X-Goog-Resource-State');

        // Erster Ping nach Watch-Registrierung — nur bestätigen
        if ($resourceState === 'sync') {
            Log::info('Google Calendar Webhook: Sync-Ping empfangen', ['channel_id' => $channelId]);
            return response('', 200);
        }

        if (!$channelId || $resourceState !== 'exists') {
            return response('', 200);
        }

        $integration = CalendarIntegration::where('watch_channel_id', $channelId)->first();

        if (!$integration) {
            Log::warning('Google Calendar Webhook: Unbekannter Channel', [
                'channel_id' => $channelId,
            ]);
            return response('', 200);
        }

        Log::info('Google Calendar Webhook: Änderung empfangen → Sync starten', [
            'user_id'    => $integration->user_id,
            'channel_id' => $channelId,
        ]);

        // Pull-Sync als Job dispatchen (nicht blockierend)
        SyncFromGoogleCalendarJob::dispatch($integration->id);

        return response('', 200);
    }
}
