<?php

namespace App\Livewire\Integration;

use App\Jobs\SyncFromGoogleCalendarJob;
use App\Models\CalendarIntegration;
use App\Services\GoogleCalendarService;
use Livewire\Component;

class Index extends Component
{
    public bool   $modalOpen     = false;
    public string $activeProvider = '';   // google | outlook

    // für Sync-Mode-Änderung live im Modal
    public string $syncMode = 'read';

    public function openModal(string $provider): void
    {
        $this->activeProvider = $provider;
        $integration = $this->getIntegration($provider);
        $this->syncMode = $integration?->sync_mode ?? 'read';
        $this->modalOpen = true;
    }

    public function closeModal(): void
    {
        $this->modalOpen     = false;
        $this->activeProvider = '';
    }

    public function updateSyncMode(string $mode): void
    {
        if (!$this->canUseSyncMode()) return;

        CalendarIntegration::where('user_id', auth()->id())
            ->where('provider', $this->activeProvider)
            ->update(['sync_mode' => $mode]);

        $this->syncMode = $mode;

        // Watch (Push-Benachrichtigungen) registrieren wenn Pull-Modus aktiv
        if ($this->activeProvider === 'google' && in_array($mode, ['read', 'both'])) {
            $integration = $this->getIntegration('google');
            if ($integration) {
                app(GoogleCalendarService::class)->createWatch($integration->fresh());
            }
        }
    }

    public function disconnect(): void
    {
        $integration = $this->getIntegration($this->activeProvider);

        // Watch stoppen bevor wir die Integration löschen
        if ($integration && $this->activeProvider === 'google') {
            app(GoogleCalendarService::class)->stopWatch($integration);
        }

        CalendarIntegration::where('user_id', auth()->id())
            ->where('provider', $this->activeProvider)
            ->delete();

        $this->closeModal();
    }

    /**
     * Manueller Sync-Button: sofort Pull von Google starten.
     */
    public function syncNow(): void
    {
        $integration = $this->getIntegration('google');

        if (!$integration || !in_array($integration->sync_mode, ['read', 'both'])) {
            return;
        }

        SyncFromGoogleCalendarJob::dispatch($integration->id);

        $this->dispatch('notify', [
            'type'    => 'success',
            'message' => 'Sync gestartet — Termine werden gleich importiert.',
        ]);
    }

    /**
     * Watch registrieren (bei Sync-Mode-Änderung auf read|both oder manuell).
     */
    public function registerWatch(): void
    {
        $integration = $this->getIntegration('google');
        if (!$integration) return;

        app(GoogleCalendarService::class)->createWatch($integration);

        $this->dispatch('notify', [
            'type'    => 'success',
            'message' => 'Push-Benachrichtigungen aktiviert.',
        ]);
    }

    // ── Helpers ──────────────────────────────────────────────────────────

    public function getIntegration(string $provider): ?CalendarIntegration
    {
        return auth()->user()->calendarIntegration($provider);
    }

    public function canUseSyncMode(): bool
    {
        return auth()->user()->hasFeature('calendar_sync');
    }

    public function render()
    {
        $google  = $this->getIntegration('google');
        $outlook = $this->getIntegration('outlook');

        return view('livewire.integration.index', [
            'google'          => $google,
            'outlook'         => $outlook,
            'canSync'         => $this->canUseSyncMode(),
            'justConnected'   => session('integration_connected'),
            'connectionError' => session('integration_error'),
        ])->layout('layouts.app');
    }
}
