<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        // Process scheduled mailings every minute
        $schedule->command('mailings:process-scheduled')->everyMinute();

        // Clean up offline users every minute
        $schedule->command('presence:cleanup-offline --minutes=5')->everyMinute();

        // Clean up old presence data weekly (safety net for real-time cleanup)
        $schedule->command('presence:cleanup')->weekly();

        // Anonymize old IP addresses weekly for GDPR compliance
        $schedule->command('ip:cleanup')
            ->weekly()
            ->mondays()
            ->at('03:00')
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/ip-cleanup.log'));

        // Daily Scout reindex backup (runs at 4 AM)
        // Note: Commented out - scout:daily-reindex command doesn't exist
        // Scout indexes are kept in sync automatically via model observers
        // Manual reindexing can be done with: php artisan scout:import "App\Models\{Model}"
        // $schedule->command('scout:daily-reindex')
        //     ->dailyAt('04:00')
        //     ->withoutOverlapping()
        //     ->runInBackground()
        //     ->appendOutputTo(storage_path('logs/scout-reindex.log'));

        // Process bounce emails every hour (requires IMAP configuration)
        $schedule->command('mailings:process-bounces --delete')
            ->hourly()
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/bounce-processing.log'))
            ->when(fn() => config('app.bounce_processing_enabled', false));

        // Clean up old soft bounce records weekly (keep hard bounces, requires IMAP configuration)
        $cleanupConfig = timebank_config('mailing.bounce_thresholds.automatic_cleanup');
        $cleanupDays = $cleanupConfig['cleanup_days'] ?? 90;
        $cleanupTime = $cleanupConfig['time'] ?? '03:00';
        $dayOfWeek = $cleanupConfig['day_of_week'] ?? 1; // Monday

        $schedule->command("mailings:manage-bounces cleanup --days={$cleanupDays}")
            ->weekly()
            ->when(function () use ($dayOfWeek) {
                return now()->dayOfWeek === $dayOfWeek && config('app.bounce_processing_enabled', false);
            })
            ->at($cleanupTime);

        // Send expiry warning and expired notification emails for calls
        $schedule->command('calls:process-expiry')
            ->daily()
            ->at('08:00')
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/call-expiry.log'));

        // Mark profiles as inactive when they haven't logged in for configured days
        $schedule->command('profiles:mark-inactive')
            ->daily()
            ->at('01:30')
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/mark-inactive-profiles.log'));

        // Process inactive profiles daily (send warnings and delete profiles)
        $schedule->command('profiles:process-inactive')
            ->daily()
            ->at('02:00')
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/inactive-profiles.log'));

        // Permanently delete (anonymize) profiles that exceeded grace period after deletion
        $schedule->command('profiles:permanently-delete-expired')
            ->daily()
            ->at('02:30')
            ->withoutOverlapping()
            ->appendOutputTo(storage_path('logs/permanent-deletions.log'));

        // Trim inactive profile log files monthly (keep last 30 days)
        $schedule->command('profiles:trim-logs --days=30')
            ->monthly()
            ->at('03:30')
            ->withoutOverlapping();

        // Delete expired WireChat disappearing messages
        $wirechatSchedule = timebank_config('wirechat.disappearing_messages.cleanup_schedule', 'everyFiveMinutes');
        $wirechatEnabled = timebank_config('wirechat.disappearing_messages.enabled', true);

        if ($wirechatEnabled) {
            $schedule->command('wirechat:delete-expired')
                ->$wirechatSchedule()
                ->withoutOverlapping()
                ->appendOutputTo(storage_path('logs/wirechat-cleanup.log'));
        }
    }

    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__ . '/Commands');
        require base_path('routes/console.php');
    }
}
