<?php

declare(strict_types=1);

namespace App\Commands;

use App\Service\Utils\PathUtils;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Contracts\Service\Attribute\Required;

/**
 * Post install script: create or replace the symlink .env.local pointing
 * to the .env file matching the current environment.
 *
 * @see doc/env.md
 */
#[AsCommand(
    name: 'ot:setup:env',
    description: 'Setup the env file according to the current host'
)]
class SetupEnvCommand extends Command
{
    public const ENVIRONMENTS_FILES = [
        'ap2i' => '.env.docker',
        'prod-v2' => '.env.prod',
        'test-v2' => '.env.test',
        'test1' => '.env.test1',
        'test2' => '.env.test2',
        'test3' => '.env.test3',
        'test4' => '.env.test4',
        'test5' => '.env.test5',
        'test6' => '.env.test6',
        'test7' => '.env.test7',
        'test8' => '.env.test8',
        'test9' => '.env.test9',
        'ci' => '.env.staging',
    ];

    private string $projectDir;

    #[Required]
    public function setProjectDir(string $projectDir): void
    {
        $this->projectDir = $projectDir;
    }

    /**
     * Configures the command.
     */
    protected function configure(): void
    {
        $this->addOption(
            'host',
            null,
            InputOption::VALUE_REQUIRED,
            "Use this hostname instead of the current's host name."
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if ($input->getOption('host')) {
            $hostname = $input->getOption('host');
        } elseif (getenv('HOST')) {
            $hostname = getenv('HOST');
        } else {
            $hostname = gethostname();
        }

        if (!array_key_exists($hostname, self::ENVIRONMENTS_FILES)) {
            throw new \RuntimeException('Critical : unknown environment ['.$hostname.']');
        }

        $envFile = PathUtils::join($this->projectDir, 'env', self::ENVIRONMENTS_FILES[$hostname]);
        $symlinkLocation = PathUtils::join($this->projectDir, '.env.local');

        if (file_exists($symlinkLocation)) {
            unlink($symlinkLocation);
            $output->writeln($symlinkLocation.' was deleted');
        }

        symlink($envFile, $symlinkLocation);
        $output->writeln('Symlink created : '.$symlinkLocation.' => '.$envFile);

        return Command::SUCCESS;
    }
}
