<?php

namespace classes;

use Exception;


class Environment
{
    /**
     * Loads the environment configuration from the specified file and
     * populates the $_ENV superglobal with the parsed data.
     *
     * @param string $envFile Path to the environment file.
     * @return void
     */
    public static function load(string $envFile): void
    {
        if (!file_exists($envFile))
        {
            RDTResponse::fail('Missing environment file');
            // throw new Exception('Missing environment file');
        }

        $_ENV = parse_ini_file($envFile, true, INI_SCANNER_TYPED);

        // Creates services URLs
        if (isset($_ENV['services']))
        {
            self::createServicesURLs();
        }
    }

    /**
     * Generates service URLs for entries in the 'services' configuration of the environment
     * and adds them to the $_ENV['services'] array.
     *
     * @return void
     */
    private static function createServicesURLs(): void
    {
        foreach ($_ENV['services'] as $key => $servicePort)
        {
            if (strpos($key, "PORT") !== false)
            {
                $serviceName = explode('_', $key)[0];
                $serviceURLKey = strtoupper($serviceName) . "_SERVICE_URL";
                $_ENV['services'][$serviceURLKey] = "{$_ENV['services']['BASE_URL']}:{$servicePort}/" . strtolower($serviceName) ."/";
            }
        }
    }
}