<?php

namespace App\Tests\Command;

use App\Command\PurgeCommand;
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\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;

#[AllowMockObjectsWithoutExpectations]
class PurgeCommandTest extends TestCase
{
    private MockObject&HttpClientInterface $httpClient;

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

    public function testExecuteSuccess()
    {
        $response = $this->createMock(ResponseInterface::class);
        $response->method('toArray')->willReturn(['success' => true]);

        $this->httpClient->expects($this->once())
            ->method('request')
            ->with('POST', $this->stringContains('purge_cache'), $this->anything())
            ->willReturn($response);

        $command = new PurgeCommand($this->httpClient, 'zone_id', 'api_token');
        $application = new Application();
        $application->addCommand($command);
        $commandTester = new CommandTester($application->find('app:purge-cloudflare'));

        $commandTester->execute([]);

        $this->assertStringContainsString('entièrement vidé', $commandTester->getDisplay());
        $this->assertEquals(0, $commandTester->getStatusCode());
    }

    public function testExecuteFailure()
    {
        $response = $this->createMock(ResponseInterface::class);
        $response->method('toArray')->willReturn([
            'success' => false,
            'errors' => [['message' => 'Simulated API Error']]
        ]);

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

        $command = new PurgeCommand($this->httpClient, 'zone_id', 'api_token');
        $application = new Application();
        $application->addCommand($command);
        $commandTester = new CommandTester($application->find('app:purge-cloudflare'));

        $commandTester->execute([]);

        $this->assertStringContainsString('Erreur Cloudflare : Simulated API Error', $commandTester->getDisplay());
        $this->assertEquals(1, $commandTester->getStatusCode());
    }
}
