<?php

namespace App\Tests\Command;

use App\Command\DeployConfigCommand;
use PHPUnit\Framework\Attributes\AllowMockObjectsWithoutExpectations;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

#[AllowMockObjectsWithoutExpectations]
class DeployConfigCommandTest extends TestCase
{
    private MockObject&ParameterBagInterface $parameterBag;
    private MockObject&HttpClientInterface $httpClient;

    protected function setUp(): void
    {
        $this->parameterBag = $this->createMock(ParameterBagInterface::class);
        $this->httpClient = $this->createMock(HttpClientInterface::class);
    }

    public function testExecuteMissingToken()
    {
        // Setup
        $this->parameterBag->method('get')->willReturn('/tmp');
        
        // Remove CLOUDFLARE_DEPLOY from env if it exists (for this test)
        $originalEnv = $_ENV['CLOUDFLARE_DEPLOY'] ?? null;
        unset($_ENV['CLOUDFLARE_DEPLOY']);
        unset($_SERVER['CLOUDFLARE_DEPLOY']); // Safety

        // Execute
        $command = new DeployConfigCommand($this->parameterBag, $this->httpClient);
        $application = new Application();
        $application->addCommand($command);
        $commandTester = new CommandTester($application->find('app:deploy:config'));

        $commandTester->execute([]);
        
        // Restore Env
        if ($originalEnv) $_ENV['CLOUDFLARE_DEPLOY'] = $originalEnv;

        // Assert
        $output = $commandTester->getDisplay();
        $this->assertStringContainsString('La clé API Cloudflare (CLOUDFLARE_DEPLOY) est manquante', $output);
        $this->assertEquals(1, $commandTester->getStatusCode());
    }

    public function testExecuteSuccess()
    {
        // Setup
        $this->parameterBag->method('get')->willReturn(sys_get_temp_dir());
        $_ENV['CLOUDFLARE_DEPLOY'] = 'test_token'; // Mock environment variable

        // --- Mocking Cloudflare API Responses ---

        // 1. Zone ID Request
        $zoneResponse = $this->createMock(ResponseInterface::class);
        $zoneResponse->method('toArray')->willReturn([
            'result' => [['id' => 'zone_123']]
        ]);

        // 2. Rulesets List Request (Found existing ruleset)
        $rulesetsListResponse = $this->createMock(ResponseInterface::class);
        $rulesetsListResponse->method('toArray')->willReturn([
            'result' => [
                ['id' => 'rs_123', 'phase' => 'http_request_cache_settings']
            ]
        ]);

        // 3. Get Specific Ruleset Rules
        $rulesResponse = $this->createMock(ResponseInterface::class);
        $rulesResponse->method('toArray')->willReturn([
            'result' => ['rules' => []]
        ]);

        // 4. Update Ruleset (PUT)
        $updateResponse = $this->createMock(ResponseInterface::class);
        $updateResponse->method('toArray')->willReturn(['success' => true]);

        // Configure HttpClient Sequence using Consecutive Calls
        $this->httpClient->expects($this->exactly(4))
            ->method('request')
            ->willReturnOnConsecutiveCalls(
                $zoneResponse,
                $rulesetsListResponse,
                $rulesResponse,
                $updateResponse
            );

        // Execute
        $command = new DeployConfigCommand($this->parameterBag, $this->httpClient);
        $application = new Application();
        $application->addCommand($command);
        $commandTester = new CommandTester($application->find('app:deploy:config'));

        $commandTester->execute([]);

        // Assert
        $output = $commandTester->getDisplay();
        $this->assertStringContainsString('Ruleset Cloudflare mis à jour', $output);
        $this->assertEquals(0, $commandTester->getStatusCode());
    }

    public function testExecuteZoneNotFound()
    {
        // Setup
        $this->parameterBag->method('get')->willReturn(sys_get_temp_dir());
        $_ENV['CLOUDFLARE_DEPLOY'] = 'test_token';

        // Zone Request - Empty Result
        $zoneResponse = $this->createMock(ResponseInterface::class);
        $zoneResponse->method('toArray')->willReturn(['result' => []]);

        $this->httpClient->expects($this->once())
            ->method('request')
            ->willReturn($zoneResponse);

        // Execute
        $command = new DeployConfigCommand($this->parameterBag, $this->httpClient);
        $application = new Application();
        $application->addCommand($command);
        $commandTester = new CommandTester($application->find('app:deploy:config'));

        $commandTester->execute([]);

        // Assert
        $output = $commandTester->getDisplay();
        $this->assertStringContainsString('Zone introuvable', $output);
        $this->assertEquals(1, $commandTester->getStatusCode());
    }
}
