<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Dotenv\Adapter;

use Gls\GlsPoland\Dotenv\DotenvLoaderInterface;
use Symfony\Component\Dotenv\Dotenv;

final class DotenvLoader implements DotenvLoaderInterface
{
    private $dotenv;

    public function __construct(?Dotenv $dotenv = null)
    {
        $this->dotenv = $dotenv ?? new Dotenv();
    }

    public function loadEnv(string $path, string $varName = 'APP_ENV', string $defaultEnv = 'dev', array $testEnvs = ['test']): void
    {
        if (is_callable([$this->dotenv, 'loadEnv'])) {
            $this->dotenv->loadEnv($path, $varName, $defaultEnv, $testEnvs);
        } else {
            $this->doLoadEnv($path, $varName, $defaultEnv, $testEnvs);
        }
    }

    private function doLoadEnv(string $path, string $varName, string $defaultEnv, array $testEnvs): void
    {
        if (file_exists($path) || !file_exists($p = "$path.dist")) {
            $this->dotenv->load($path);
        } else {
            $this->dotenv->load($p);
        }

        if (null === $env = $_SERVER[$varName] ?? $_ENV[$varName] ?? null) {
            $this->dotenv->populate([$varName => $env = $defaultEnv]);
        }

        if (!in_array($env, $testEnvs, true) && file_exists($p = "$path.local")) {
            $this->dotenv->load($p);
        }

        if ('local' === $env) {
            return;
        }

        if (file_exists($p = "$path.$env")) {
            $this->dotenv->load($p);
        }

        if (file_exists($p = "$path.$env.local")) {
            $this->dotenv->load($p);
        }
    }
}
