<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Schedule;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');

Schedule::command('users:cleanup-deleted')->daily();
Schedule::command('subscriptions:check-expired')->daily();
Schedule::command('affiliates:process-qualifications')->daily();
Schedule::command('credits:monthly-reset')->monthlyOn(1, '00:05');
Schedule::command('mail:cleanup')->everyMinute();

// Google Calendar Pull-Sync: alle 5 Minuten
// Push-Webhook via Google Watch ist registriert aber kann je nach Firewall/Cloudflare
// blockiert werden — 5-Minuten-Polling ist der zuverlässige Fallback
Schedule::call(function () {
    \App\Models\CalendarIntegration::where('provider', 'google')
        ->whereIn('sync_mode', ['read', 'both'])
        ->each(function ($integration) {
            \App\Jobs\SyncFromGoogleCalendarJob::dispatch($integration->id);
        });
})->everyFiveMinutes()->name('google-calendar-sync');

// Event Reminders: jede Minute, Dedup via sent_reminders Tabelle
Schedule::command('reminders:schedule')->everyMinute();

// Allgemeine Automationen (Geburtstag, Agenda, etc.): jede Minute, intern zeitgesteuert
Schedule::command('automations:run')->everyMinute();

// Google Watch erneuern: täglich Watches prüfen die in 24h ablaufen
Schedule::call(function () {
    \App\Models\CalendarIntegration::where('provider', 'google')
        ->whereIn('sync_mode', ['read', 'both'])
        ->where(function ($q) {
            $q->whereNull('watch_expires_at')
              ->orWhere('watch_expires_at', '<=', now()->addDay());
        })
        ->each(function ($integration) {
            app(\App\Services\GoogleCalendarService::class)->createWatch($integration);
        });
})->daily()->name('google-calendar-watch-renewal');
