<?php

namespace App\Command;

use Doctrine\DBAL\Connection;
use Doctrine\Persistence\ManagerRegistry;
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\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class DatabaseBackupCommand extends Command
{
    /**
     * @var string
     */
    private string $projectDirectory;

    /**
     * @var SymfonyStyle
     */
    private SymfonyStyle $io;

    protected static $defaultName = 'app:database-backup';
    /**
     * @var ManagerRegistry
     */
    private ManagerRegistry $managerRegistry;

    public function __construct(
        ManagerRegistry $managerRegistry,
        string $projectDirectory
    ) {
        parent::__construct();
        $this->managerRegistry = $managerRegistry;
        $this->projectDirectory = $projectDirectory;
    }

    protected function configure(): void
    {
        $this->setDescription('Générer un backup de la base de données');
    }

    public function initialize(InputInterface $input, OutputInterface $output): void
    {
        $this->io = new SymfonyStyle($input, $output);
    }

    // protected function execute(InputInterface $input, OutputInterface $output): int
    // {
    //     $fileSystem = new Filesystem();
    //     $backupDirectory = "$this->projectDirectory/var/backup";

    //     if ($fileSystem->exists($backupDirectory) === true){
    //         $fileSystem->remove($backupDirectory);
    //     }

    //     try {
    //         $fileSystem->mkdir($backupDirectory, 0700);
    //     }catch (IOException $error){
    //         throw new IOException($error);
    //     }

    //     /** @var Connection $databaseConnection */
    //     $databaseConnection = $this->managerRegistry->getConnection();
    //     [
    //         'host' => $databaseHost,
    //         'port' => $databasePort,
    //         'user' => $databaseUsername,
    //         'password' => $databasePassword,
    //         'dbname' => $databaseName,
    //     ] = $databaseConnection->getParams();

    //     $filePathTarget = "--result-file=$backupDirectory/backup.sql";
    //     $command = [
    //         'mysqldump',
    //         '--host', // -h
    //         $databaseHost,
    //         '--port', // -P
    //         $databasePort,
    //         '--user', // -u
    //         $databaseUsername,
    //         '--password'. $databasePassword, // -p
    //         $databaseName,
    //         '--databases', // If you want to create a CREATE DATABASE statement for an import via PHPMYADMIN for
    //         $filePathTarget
    //     ];

    //     if ($databasePassword === ''){
    //         $command = [
    //             'mysqldump',
    //             '--host',
    //             $databaseHost,
    //             '--port',
    //             $databasePort,
    //             '--user',
    //             $databaseUsername,
    //             $databaseName,
    //             $filePathTarget
    //         ];
    //     }

    //     $process = new Process($command);
    //     $process->setTimeout(90);
    //     $process->run();

    //     if ($process->isSuccessful() === false){
    //         throw new ProcessFailedException($process);
    //     }

    //     $this->io->success('Sauvegarde de la base de données réussie');

    //     return Command::SUCCESS;
    // }


    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $fileSystem = new Filesystem();
        $backupDirectory = "$this->projectDirectory/var/backup";

        if ($fileSystem->exists($backupDirectory) === true) {
            $fileSystem->remove($backupDirectory);
        }

        try {
            $fileSystem->mkdir($backupDirectory, 0700);
        } catch (IOException $error) {
            throw new IOException($error);
        }

        /** @var Connection $databaseConnection */
        $databaseConnection = $this->managerRegistry->getConnection();
        [
            'host' => $databaseHost,
            'port' => $databasePort,
            'user' => $databaseUsername,
            'password' => $databasePassword,
            'dbname' => $databaseName,
        ] = $databaseConnection->getParams();

        $backupFile = "$backupDirectory/backup.sql";

        // ✅ Correction de la commande
        $command = [
            'mysqldump',
            "--host=$databaseHost",
            "--port=$databasePort",
            "--user=$databaseUsername",
            "--password=$databasePassword",
            '--result-file=' . $backupFile,
            $databaseName,
        ];

        // 🔧 Si mysqldump n'est pas dans le PATH sous Windows :
        // $command[0] = 'C:\xampp\mysql\bin\mysqldump.exe'; // exemple

        $process = new Process($command);
        $process->setTimeout(90);
        $process->run();

        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        if (!file_exists($backupFile)) {
            throw new \RuntimeException("Le fichier $backupFile n’a pas été créé par mysqldump !");
        }

        $this->io->success('Sauvegarde de la base de données réussie.');
        return Command::SUCCESS;
    }
}
