<?php

declare(strict_types=1);

namespace App\Command;

use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Contracts\HttpClient\HttpClientInterface;

#[AsCommand(
    name: 'app:purge-cloudflare',
    description: 'Purge le cache complet de Cloudflare pour reservation.ludikevent.fr',
)]
class PurgeCommand extends Command
{
    private HttpClientInterface $httpClient;
    private string $cloudflareZoneId;
    private string $cloudflareApiToken;

    public function __construct(
        HttpClientInterface $httpClient,
        // Ces paramètres seront à configurer dans ton .env et services.yaml
        string $cloudflareZoneId = '343636c7cfbfeceef50f25e88ea1a0cc',
        string $cloudflareApiToken = 'Z0fd473mtX1trS2bHaU74U8yo9jTAfz09iy_SL2m'
    ) {
        parent::__construct();
        $this->httpClient = $httpClient;
        $this->cloudflareZoneId = $cloudflareZoneId;
        $this->cloudflareApiToken = $cloudflareApiToken;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $response = $this->httpClient->request('POST', "https://api.cloudflare.com/client/v4/zones/{$this->cloudflareZoneId}/purge_cache", [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->cloudflareApiToken,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'purge_everything' => true, // C'est ici que l'on vide le domaine entier
            ],
        ]);

        $result = $response->toArray();

        if ($result['success']) {
            $io->success('Le cache de reservation.ludikevent.fr a été entièrement vidé.');
            return Command::SUCCESS;
        }

        $io->error('Erreur Cloudflare : ' . $result['errors'][0]['message']);
        return Command::FAILURE;
    }
}
