<?php

namespace Tests\Feature;

use Illuminate\Support\Facades\Artisan;
use Tests\TestCase;

class CronExecutionTest extends TestCase
{
    public function test_it_executes_schedule_run_by_default(): void
    {
        Artisan::shouldReceive('call')
            ->once()
            ->with('schedule:run')
            ->andReturn(0);

        Artisan::shouldReceive('output')
            ->once()
            ->andReturn('No scheduled commands are ready to run.');

        $response = $this->postJson('/api/cron/run');

        $response->assertOk()
            ->assertJson([
                'status' => 'success',
                'command' => 'schedule:run',
                'exit_code' => 0,
            ]);
    }

    public function test_it_executes_allowed_command(): void
    {
        Artisan::shouldReceive('call')
            ->once()
            ->with('platforms:refresh-tokens')
            ->andReturn(0);

        Artisan::shouldReceive('output')
            ->once()
            ->andReturn('Tokens refreshed.');

        $response = $this->postJson('/api/cron/run', [
            'command' => 'platforms:refresh-tokens',
        ]);

        $response->assertOk()
            ->assertJson([
                'status' => 'success',
                'command' => 'platforms:refresh-tokens',
                'exit_code' => 0,
            ]);
    }

    public function test_it_rejects_unallowed_commands(): void
    {
        $response = $this->postJson('/api/cron/run', [
            'command' => 'migrate:fresh',
        ]);

        $response->assertStatus(400)
            ->assertJson([
                'status' => 'error',
                'message' => 'Command not allowed',
            ]);
    }

    public function test_it_enforces_token_when_configured(): void
    {
        config(['app.cron_token' => 'secret123']);

        // Missing token -> 401
        $this->postJson('/api/cron/run')->assertStatus(401);

        // Invalid token -> 401
        $this->postJson('/api/cron/run', [], ['X-Cron-Token' => 'wrong'])->assertStatus(401);

        // Valid token via header -> 200
        Artisan::shouldReceive('call')
            ->once()
            ->with('schedule:run')
            ->andReturn(0);
        Artisan::shouldReceive('output')
            ->once()
            ->andReturn('Ran successfully');

        $this->postJson('/api/cron/run', [], ['X-Cron-Token' => 'secret123'])
            ->assertOk();
    }
}
