<?php

it('wires cron workers through schema, CLI, scheduler, and superuser routes', function (): void {
    $schema = file_get_contents(app_path('classes/cron_schema_bootstrap.php'));
    $worker = file_get_contents(app_path('classes/cron_worker.php'));
    $scheduler = file_get_contents(app_path('classes/cron_scheduler.php'));
    $cli = file_get_contents(app_path('cli.php'));
    $route = file_get_contents(app_path('routes/cronRoute.php'));
    $manager = file_get_contents(app_path('classes/release_manager.php'));

    expect($schema)->toContain('CREATE TABLE IF NOT EXISTS cron_worker_state');
    expect($schema)->toContain('last_heartbeat_at');
    expect($schema)->toContain('last_stale_run_count');
    expect($schema)->toContain('force_run TINYINT(1) NOT NULL DEFAULT 0');

    expect($worker)->toContain('CRON_WORKER_POLL_SECONDS');
    expect($worker)->toContain('CRON_WORKER_HEARTBEAT_SECONDS');
    expect($worker)->toContain('CRON_WORKER_RELEASE_TARGET_ID');
    expect($worker)->toContain('markExpiredRunningRuns');
    expect($worker)->toContain('runDue($this->source)');

    expect($scheduler)->toContain('function markExpiredRunningRuns');
    expect($scheduler)->toContain('function queueTaskRun');
    expect($scheduler)->toContain('function queuedRuns');
    expect($scheduler)->toContain('function runQueuedRun');
    expect($scheduler)->toContain("WHERE status = 'queued'");
    expect($scheduler)->toContain("SET status = 'running'");
    expect($scheduler)->toContain("r.status = 'timed_out'");
    expect($scheduler)->toContain('s.current_run_id = NULL');

    expect($cli)->toContain("case 'cron-worker'");
    expect($cli)->toContain('new \\classes\\cron_worker()');

    expect($route)->toContain('/superuser/cron/workers');
    expect($route)->toContain('/superuser/cron/workers/deploy');
    expect($route)->toContain('$response->success($result, 202)');
    expect($route)->toContain('queueTaskRun(');
    expect($route)->toContain('$response->success($run, 202)');
    expect($route)->toContain('superuser_cron_view');
    expect($route)->toContain('superuser_cron_manage');
    expect($route)->toContain('superuser_coolify_manage');

    expect($manager)->toContain("private const CRON_WORKER_APP = 'cron'");
    expect($manager)->toContain("private const CRON_WORKER_START_COMMAND = 'php index.php run cron-worker'");
    expect($manager)->toContain('deployCronWorkerAfterApiDeployment');
    expect($manager)->toContain('deployment_kind = \'cron_worker\'');
    expect($manager)->toContain('createCronWorkerDeploymentRecord');
    expect($manager)->toContain('waiting_for_heartbeat');
    expect($manager)->toContain('cronWorkerAutoprovisionRequired');
    expect($manager)->toContain('cron_worker_autoprovision_disabled');
    expect($manager)->toContain('cron_worker_deploy_failed');
    expect($manager)->toContain('auto_deploy = 0');
});
