<?php 


namespace Lcmigrator\LcMigrator\FlavourManager;
use Lcmigrator\LcMigrator\Exceptions\InvalidArgumentException;
use Lcmigrator\LcMigrator\Exceptions\RuntimeException;

/**
 * Flavor Manager For WordPress Plugin
 * That helps you to easily manage your configurations for different environments.
 */
class FlavourManager {
    private string $flavour;
    private array $config;
    private array $defaultValues;
    private const ALLOWED_FLAVOURS = ['dev', 'staging', 'production'];

    public function __construct(string $flavour = 'dev', array $defaultValues = []) {
        $flavour = strtolower($flavour); // Convert to lowercase
        if (!in_array($flavour, self::ALLOWED_FLAVOURS)) {
            throw new InvalidArgumentException('Invalid flavour. Must be dev, staging, or production');
        }
        
        $this->flavour = $flavour;
        $this->defaultValues = $defaultValues;
        $this->loadConfig();
    }

    private function loadConfig(): void {
        $configFile = __DIR__ . "/config/_{$this->flavour}.json";
        
        if (!file_exists($configFile)) {
            throw new RuntimeException(esc_html("Configuration file not found: {$configFile}"));
        }

        $jsonContent = file_get_contents($configFile);
        $config = json_decode($jsonContent, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException(esc_html('Invalid JSON in configuration file: ' . json_last_error_msg()));
        }

        $this->config = $config;
    }

    /**
     * Function to get the value of a configuration key
     * @param string $key
     * @param mixed $default
     */
    public function get(string $key, $default = null) {
        return $this->config[$key] ?? $this->defaultValues[$key] ?? null;
    }

    /**
     * Function to set the flavour
     * @param string $flavour
     * @throws \InvalidArgumentException
     * @return void
     */
    public function setFlavour(string $flavour): void {
        if (!in_array($flavour, self::ALLOWED_FLAVOURS)) {
            throw new InvalidArgumentException('Invalid flavour. Must be dev, staging, or production');
        }
        
        $this->flavour = $flavour;
        $this->loadConfig();
    }

    /**
     * Returns The Entire Loaded Configuration
     * @return array
     */
    public function getAllConfig(): array {
        return $this->config;
    }
}
