<?php

namespace App\Observers;

use App\Models\CalendarIntegration;
use App\Models\Event;
use App\Services\GoogleCalendarService;
use Illuminate\Support\Facades\Log;

/**
 * Pusht lokale Event-Änderungen zu Google Calendar,
 * sofern der User Google verbunden hat und sync_mode = write|both.
 *
 * Sync-Schleifen werden durch GoogleCalendarService::$syncing verhindert:
 * Beim Import von Google-Daten ist das Flag true → Observer überspringt den Push.
 */
class EventObserver
{
    public function created(Event $event): void
    {
        $this->push($event);
    }

    public function updated(Event $event): void
    {
        $this->push($event);
    }

    public function deleted(Event $event): void
    {
        // Kein Push wenn Import läuft
        if (GoogleCalendarService::$syncing) return;

        if (!$event->google_event_id) return;

        $integration = $this->getWritableIntegration($event->user_id);
        if (!$integration) return;

        app(GoogleCalendarService::class)->deleteEvent($event->google_event_id, $integration);

        Log::info('Google Calendar: Event gelöscht', [
            'event_id'        => $event->id,
            'google_event_id' => $event->google_event_id,
        ]);
    }

    // ── Intern ────────────────────────────────────────────────────────────

    private function push(Event $event): void
    {
        // Kein Push wenn wir gerade von Google importieren (verhindert Schleife)
        if (GoogleCalendarService::$syncing) return;

        $integration = $this->getWritableIntegration($event->user_id);
        if (!$integration) return;

        app(GoogleCalendarService::class)->pushEvent($event, $integration);

        Log::info('Google Calendar: Event gepusht', [
            'event_id'        => $event->id,
            'google_event_id' => $event->google_event_id,
        ]);
    }

    private function getWritableIntegration(string $userId): ?CalendarIntegration
    {
        return CalendarIntegration::where('user_id', $userId)
            ->where('provider', 'google')
            ->whereIn('sync_mode', ['write', 'both'])
            ->first();
    }
}
