<?php

namespace Tests\Feature;

use Illuminate\Console\Scheduling\CommandBuilder;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schedule as ScheduleFacade;
use Mockery;
use Psr\Log\LoggerInterface;
use Tests\TestCase;

class CronExecutionTest extends TestCase
{
    public function test_cron_log_uses_the_existing_daily_log_retention(): void
    {
        $this->assertSame('daily', config('logging.channels.cron.driver'));
        $this->assertSame(storage_path('logs/cron.log'), config('logging.channels.cron.path'));
        $this->assertSame(config('logging.channels.daily.max_files'), config('logging.channels.cron.max_files'));
    }

    public function test_all_scheduled_commands_use_php_85_without_changing_their_timings(): void
    {
        Artisan::call('schedule:list');
        $originalBinary = getenv('PHP_BINARY');
        $schedule = new Schedule;
        ScheduleFacade::swap($schedule);

        try {
            putenv('PHP_BINARY=/usr/bin/php');
            require base_path('routes/console.php');
            $events = $schedule->events();

            $this->assertCount(9, $events);
            $this->assertSame([
                '* * * * *', '0 0 * * *', '25 * * * *', '20 6 * * *', '*/15 * * * *',
                '0 2 * * *', '0 0 * * *', '0 0 * * *', '10 3 * * *',
            ], array_map(fn ($event): string => $event->expression, $events));

            foreach ($events as $event) {
                $this->assertMatchesRegularExpression('/^\x27?\/usr\/bin\/php8\.5\x27?\s/', $event->command);
                $this->assertStringStartsWith(storage_path('logs/schedule-'), $event->output);
                $command = (new CommandBuilder)->buildCommand($event);
                $this->assertSame($event->runInBackground ? 2 : 1, substr_count($command, '/usr/bin/php8.5'));
                $this->assertStringNotContainsString("'/usr/bin/php'", $command);
            }

            config(['campaign-performance.schedule_monitor' => false]);
            $this->assertFalse($events[2]->filtersPass($this->app));
            $this->assertFalse($events[3]->filtersPass($this->app));
            $this->assertStringContainsString('monitor-adops --hourly', $events[2]->command);
            $this->assertStringContainsString('monitor-adops --daily', $events[3]->command);

            $this->assertStringContainsString('campaigns:sync-structure', $events[4]->command);
            config(['campaign-manager.schedule_sync' => false]);
            $this->assertFalse($events[4]->filtersPass($this->app));
            config(['campaign-manager.schedule_sync' => true]);
            $this->assertTrue($events[4]->filtersPass($this->app));
        } finally {
            putenv($originalBinary === false ? 'PHP_BINARY' : 'PHP_BINARY='.$originalBinary);
        }
    }

    public function test_scheduled_task_output_is_logged_and_temporary_capture_is_removed(): void
    {
        $originalBinary = getenv('PHP_BINARY');
        $schedule = new Schedule;
        ScheduleFacade::swap($schedule);
        putenv('PHP_BINARY=/usr/bin/php8.5');

        try {
            require base_path('routes/console.php');
            $event = $schedule->events()[0];
            $outputPath = $event->output;
            file_put_contents($outputPath, 'Completed with token=private-value');

            $logger = Mockery::mock(LoggerInterface::class);
            $logger->shouldReceive('log')
                ->once()
                ->with('info', 'Scheduled command completed', Mockery::on(function (array $context) use ($event): bool {
                    return $context['command'] === $event->command
                        && $context['status'] === 'success'
                        && $context['exit_code'] === 0
                        && str_contains($context['output'], 'token=[REDACTED]')
                        && ! str_contains($context['output'], 'private-value');
                }));
            Log::shouldReceive('channel')->once()->with('cron')->andReturn($logger);

            $event->finish($this->app, 0);

            $this->assertFileDoesNotExist($outputPath);
        } finally {
            putenv($originalBinary === false ? 'PHP_BINARY' : 'PHP_BINARY='.$originalBinary);
        }
    }

    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_logs_sanitized_request_and_returns_failure_status_when_artisan_fails(): void
    {
        Artisan::shouldReceive('call')
            ->once()
            ->with('platforms:refresh-tokens')
            ->andReturn(1);
        Artisan::shouldReceive('output')
            ->once()
            ->andReturn('Refresh failed for token=output-secret');

        $logger = Mockery::mock(LoggerInterface::class);
        $logger->shouldReceive('info')
            ->once()
            ->with('Cron request received', Mockery::on(function (array $context): bool {
                return $context['input']['token'] === '[REDACTED]'
                    && $context['input']['credentials']['api_key'] === '[REDACTED]'
                    && $context['cron_token_present'];
            }));
        $logger->shouldReceive('log')
            ->once()
            ->with('error', 'Cron command completed', Mockery::on(function (array $context): bool {
                return $context['command'] === 'platforms:refresh-tokens'
                    && $context['exit_code'] === 1
                    && $context['http_status'] === 500
                    && str_contains($context['output'], 'token=[REDACTED]')
                    && ! str_contains($context['output'], 'output-secret');
            }));
        Log::shouldReceive('channel')->twice()->with('cron')->andReturn($logger);

        $response = $this->postJson('/api/cron/run', [
            'command' => 'platforms:refresh-tokens',
            'token' => 'request-secret',
            'credentials' => ['api_key' => 'nested-secret'],
        ]);

        $response->assertStatus(500)
            ->assertJson([
                'status' => 'failed',
                'command' => 'platforms:refresh-tokens',
                'exit_code' => 1,
            ]);
    }

    public function test_it_rejects_unallowed_commands(): void
    {
        $logger = Mockery::mock(LoggerInterface::class);
        $logger->shouldReceive('info')
            ->once()
            ->with('Cron request received', Mockery::on(function (array $context): bool {
                return $context['input']['command'] === 'schedule:run token=[REDACTED]';
            }));
        $logger->shouldReceive('warning')
            ->once()
            ->with('Cron request rejected', Mockery::on(function (array $context): bool {
                return $context['command'] === 'schedule:run token=[REDACTED]'
                    && ! str_contains($context['command'], 'request-secret');
            }));
        Log::shouldReceive('channel')->twice()->with('cron')->andReturn($logger);

        $response = $this->postJson('/api/cron/run', [
            'command' => 'schedule:run token=request-secret',
        ]);

        $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();
    }
}
