<?php

use App\Jobs\Monitoring\WorkerHeartbeatJob;
use App\Services\System\BackupManagementService;
use App\Services\System\MaintenanceManagementService;
use App\Services\SystemConfig\SystemConfigService;
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');

/**
 * 1. Maintenance Mode Auto-Release
 */
Schedule::call(function () {
    app(MaintenanceManagementService::class)->autoCheckAndRelease();
})->everyMinute();

/**
 * 2. Queue Worker Heartbeat (Monitoring)
 */
Schedule::job(new WorkerHeartbeatJob)->everyMinute();

/**
 * 3. Activity Log, Notification & Model Cleanup
 */
Schedule::command('activitylog:clean')->daily();
Schedule::command('model:prune')->dailyAt('03:00');
Schedule::command('telescope:prune --hours=48')->dailyAt('03:05');

/**
 * 4. Weekly Backup Verification
 */
Schedule::command('backups:verify')->weeklyOn(1, '07:00'); // Every Monday at 07:00

/**
 * 5. Weekly Permission Audit (logged only, no auto-fix)
 */
Schedule::command('permissions:audit --json')->weeklyOn(1, '07:05')
    ->sendOutputTo(storage_path('logs/permission-audit.log'));

/**
 * 3. Dynamic Database Backup
 */
$settings = app(SystemConfigService::class)->all();
if (filter_var($settings['backup_db_enabled'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
    $frequency = $settings['backup_db_frequency'] ?? 'daily';
    $time = $settings['backup_db_time'] ?? '02:00';

    $backupTask = Schedule::call(function () {
        $service = app(BackupManagementService::class);
        $service->applyDynamicConfig();
        $service->createBackup();
    })->name('automated-db-backup')->withoutOverlapping();

    $cleanupTask = Schedule::command('backup:clean')->name('automated-db-cleanup')->withoutOverlapping();

    // Map frequency using switch for multi-statement arms
    switch ($frequency) {
        case 'hourly':
            // hourlyAt expects minutes (0-59), not a time string (HH:mm)
            $minute = (int) (str_contains($time, ':') ? explode(':', $time)[1] : $time);
            $backupTask->hourlyAt($minute);
            $cleanupTask->hourlyAt($minute);
            break;
        case 'weekly':
            $backupTask->weeklyOn(0, $time);
            $cleanupTask->weeklyOn(0, $time);
            break;
        case 'monthly':
            $backupTask->monthlyOn(1, $time);
            $cleanupTask->monthlyOn(1, $time);
            break;
        case 'daily':
        default:
            $backupTask->dailyAt($time);
            $cleanupTask->dailyAt($time);
            break;
    }
}

/**
 * 6. System Health Check Monitoring
 */
Schedule::command('system:health-check')->everyThirtyMinutes();

/**
 * 7. AI System Health Digest (Weekly)
 */
Schedule::command('system:send-digest')->weeklyOn(1, '08:00');

/**
 * 8. Real-time Dashboard Stats Broadcast (every minute via scheduler)
 *    Reverb pushes fresh stats to all connected admin.monitoring subscribers.
 */
Schedule::command('dashboard:broadcast-stats')->everyMinute()->withoutOverlapping();
