<?php

use App\Support\CronLogSanitizer;
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schedule;
use Illuminate\Support\Stringable;

putenv('PHP_BINARY=/usr/bin/php8.5');

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

// The scheduled worker is a fallback for environments without a persistent worker.
Schedule::command('queue:work --queue='.config('queue.connections.database.queue', 'default').' --stop-when-empty --max-time=50')
    ->everyMinute()
    ->withoutOverlapping(40)
    ->when(fn (): bool => config('queue.schedule_worker'))
    ->runInBackground();

// Daily refresh of platform OAuth access tokens expiring within 10 days (Meta 60-day, LinkedIn, Google)
Schedule::command('platforms:refresh-tokens --days=10')
    ->daily()
    ->withoutOverlapping(10)
    ->runInBackground();
Schedule::command('campaigns:monitor-adops --hourly')
    ->hourlyAt(25)
    ->withoutOverlapping(50)
    ->when(fn (): bool => (bool) config('campaign-performance.schedule_monitor'));

Schedule::command('campaigns:monitor-adops --daily')
    ->dailyAt('06:20')
    ->withoutOverlapping(120)
    ->when(fn (): bool => (bool) config('campaign-performance.schedule_monitor'));

// Read-only reconciliation of managed campaigns with their platforms.
Schedule::command('campaigns:sync-structure')
    ->everyFifteenMinutes()
    ->withoutOverlapping(30)
    ->when(fn (): bool => (bool) config('campaign-manager.schedule_sync'));

// Daily refresh of the USD exchange rates behind non-USD budget ceilings
Schedule::command('fx:refresh')->dailyAt('02:00')->withoutOverlapping(10)->runInBackground();

// Prune stale queue failures (older than 7 days) and batch metadata (older than 48 hours)
Schedule::command('queue:prune-failed --hours=168')->daily()->runInBackground();
Schedule::command('queue:prune-batches --hours=48')->daily()->runInBackground();
Schedule::command('cache:prune-expired-database')->dailyAt('03:10')->withoutOverlapping(30)->runInBackground();

$sanitizer = app(CronLogSanitizer::class);
$temporaryOutputPrefix = storage_path('logs/schedule-');

foreach (Schedule::events() as $event) {
    $command = $sanitizer->sanitizeText((string) $event->command);

    $event->before(static function () use ($command): void {
        Log::channel('cron')->info('Scheduled command started', ['command' => $command]);
    });

    $logCompletion = static function (string $level, string $status, Stringable $output) use ($command, $event, $sanitizer): void {
        Log::channel('cron')->log($level, 'Scheduled command completed', [
            'command' => $command,
            'status' => $status,
            'exit_code' => $event->exitCode,
            'output' => $sanitizer->sanitizeText((string) $output),
        ]);
    };

    $event->onSuccess(static fn (Stringable $output) => $logCompletion('info', 'success', $output));
    $event->onFailure(static fn (Stringable $output) => $logCompletion('error', 'failed', $output));
    $event->then(static function () use ($event, $temporaryOutputPrefix): void {
        if (str_starts_with($event->output, $temporaryOutputPrefix) && is_file($event->output)) {
            @unlink($event->output);
        }
    });
}
