<?php

namespace Leantime\Domain\Environment\Commands;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SyncEnvironment extends Command
{
    protected static $defaultName = 'env:sync';

    protected static $defaultDescription = 'Synchronizes environment variables to .env file';

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $output->writeln('Starting environment variable sync...');

        $envFile = base_path('.env');

        // Create or clear the .env file
        file_put_contents($envFile, '# Generated by env:sync command - '.date('Y-m-d H:i:s')."\n");

        // Get all environment variables
        foreach ($_ENV as $name => $value) {
            if (str_starts_with($name, 'LEAN_')) {
                $escapedValue = str_replace(['\\', '"', '$'], ['\\\\', '\\"', '\\$'], $value);
                file_put_contents($envFile, "{$name}=\"{$escapedValue}\"\n", FILE_APPEND);
            }
        }

        // Set proper permissions
        chmod($envFile, 0640);

        $output->writeln('Environment sync completed.');

        return Command::SUCCESS;
    }
}
