<?php

declare(strict_types=1);

namespace Apexl\Tests\Configuration\UnitTests;

use apexl\Config\Configuration;
use apexl\Config\Exceptions\InvalidConfigException;
use apexl\Config\Exceptions\MissingConfigException;
use apexl\Io\TestInfrastructure\UnitTest;
use PHPUnit\Framework\Attributes\Test;

final class ConfigurationTest extends UnitTest
{
    /**
     * @throws InvalidConfigException
     * @throws MissingConfigException
     */
    #[Test]
    function loadsPHP()
    {
        $exists = 'I Exist';
        $existsDeep = 'I Exist Deep';
        $config = new Configuration(cacheFilename: 'testConfigCache.json');

        $dir = '/tmp/io-config-test';
        $file = tempnam($dir, 'io-config-test');
        rename($file, $file .= '.php');
        $key = basename($file, '.php');
        $data = ['exists' => $exists, 'deep' => ['exists' => $existsDeep]];
        file_put_contents(
            $file,
            sprintf('<?php return %s;', var_export($data, true))
        );


        $config->load($file);

        $this->assertSame($exists, $config->get($key . '.exists'));
        $this->assertSame($existsDeep, $config->get($key . '.deep.exists'));
        $this->assertSame($data, $config->get($key));


        $this->expectException(InvalidConfigException::class);

        $config->get($key . '.doesNotExist');

        $this->expectException(InvalidConfigException::class);
        $config->get($key . '.deep.doesNotExist');

        rmdir($dir);
    }
}