<?php

namespace App\Jobs;

use App\Models\CalendarIntegration;
use App\Services\GoogleCalendarService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

/**
 * Zieht neue und geänderte Events von Google Calendar und importiert sie lokal.
 * Wird per Schedule alle 15 Minuten ausgelöst (für alle User mit sync_mode read|both).
 */
class SyncFromGoogleCalendarJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries   = 3;
    public int $timeout = 60;

    public function __construct(
        public readonly string $integrationId
    ) {}

    public function handle(GoogleCalendarService $service): void
    {
        $integration = CalendarIntegration::find($this->integrationId);

        if (!$integration) {
            Log::warning('SyncFromGoogleCalendarJob: Integration nicht gefunden', [
                'id' => $this->integrationId,
            ]);
            return;
        }

        if (!in_array($integration->sync_mode, ['read', 'both'])) {
            return; // Kein Pull für diesen Modus
        }

        Log::info('Google Calendar: Starte Pull-Sync', [
            'user_id'    => $integration->user_id,
            'sync_mode'  => $integration->sync_mode,
            'has_token'  => (bool) $integration->sync_token,
        ]);

        $service->pullEvents($integration);
    }
}
