<?php

namespace App\Console\Commands;

use Aws\SecretsManager\SecretsManagerClient;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class FetchSecrets extends Command
{
    protected $signature = 'secrets:fetch';
    protected $description = 'Fetch secrets from AWS Secrets Manager and store in the .env file';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $client = new SecretsManagerClient([
            'region' => 'us-east-1',
            'version' => 'latest',
        ]);

        $secrets = ['UserSecret', 'RDSSecret']; // Add your secret names here

        try {
            // Loop through each secret name
            foreach ($secrets as $secretName) {
                // Retrieve each secret
                $result = $client->getSecretValue([
                    'SecretId' => $secretName,
                ]);

                // Check if the secret is in JSON format
                if (isset($result['SecretString'])) {
                    $secret = $result['SecretString'];
                } else {
                    $secret = base64_decode($result['SecretBinary']);
                }

                // Decode the secret (assuming it's a JSON string)
                $secretArray = json_decode($secret, true);

                // Save each key-value pair into the .env file
                $this->setEnvironmentValues($secretArray);
            }

            $this->info('Secrets fetched and stored in the .env file successfully.');
        } catch (\Exception $e) {
            $this->error('Error fetching secrets: ' . $e->getMessage());
        }
    }
    protected function setEnvironmentValues(array $secrets)
    {
        $envFile = base_path('.env');
        $envContents = File::get($envFile);  // Load the current .env contents

        foreach ($secrets as $key => $value) {
            // Check if the key exists in the .env content
            if (preg_match("/^{$key}=/m", $envContents)) {
                // If the key exists, replace its value
                $envContents = preg_replace("/^{$key}=.*/m", "{$key}={$value}", $envContents);
            } else {
                // If the key does not exist, append it
                $envContents .= "\n{$key}={$value}";
            }
        }
        File::put($envFile, $envContents);
    }
}
