<?php

/**
 * Phinx Configuration
 * @see https://book.cakephp.org/phinx/0/en/configuration.html
 *
 * For local / environment specific config, create a phinx.local.php.  Configs will be merged recursively, with
 * local config overriding general config
 */

declare(strict_types=1);

use apexl\Config\ConfigurationInterface;
use apexl\Config\Exceptions\InvalidConfigException;
use apexl\Io\Client;
use apexl\Io\factories\ClientFactory;
use apexl\Io\factories\ContainerFactory;
use apexl\Io\modules\system\Factories\ConfigurationFactory;
use apexl\Io\services\FilePaths;
use DI\Bridge\Slim\Bridge;
use Dotenv\Dotenv;

$baseDir = __DIR__ . '/../../../../';
$filePaths = isset($GLOBALS['container']) ? $GLOBALS['container']->get(FilePaths::class) : new FilePaths($baseDir);

if (!isset($GLOBALS['container'])) {
    Dotenv::createImmutable($filePaths->basePath())->load();
}

try {
    $config = new ConfigurationFactory($filePaths, ['phinx.php'])->make();
} catch (InvalidConfigException $e) {
    die($e->getMessage());
}

if (!isset($GLOBALS['container'])) {
    $container = new ContainerFactory()->make($baseDir);

    $container->set(FilePaths::class, $filePaths);
    $container->set(ConfigurationInterface::class, $config);

    $application = Bridge::create($container);

    $GLOBALS['container'] = $container;

    $config = $container->get(ConfigurationFactory::class)->make();
}


$phinxConfig = [
    'paths' => [
        'migrations' =>
            [
                $filePaths->basePath('module/*/db/migrations'),
                $filePaths->basePath('vendor/apexl/**/src/Io/modules/**/db/migrations'),
            ],
        'seeds' =>
            [
                $filePaths->basePath('module/*/db/seeds'),
                $filePaths->basePath('vendor/apexl/**/src/Io/modules/**/db/seeds'),
            ],
    ],
    'environments' => [
        'default_migration_table' => 'phinxlog',
        'default_environment' => $_ENV['PHINX_DEFAULT_ENVIRONMENT'] ?? 'default'
    ],
    'version_order' => 'creation',
];

$local = __DIR__ . '/phinx.local.php';
$vault = __DIR__ . '/vault.php';

if (file_exists($local)) {
    $phinxConfig = array_merge_recursive($phinxConfig, include $local);
} elseif ($config->has('vault')) {
    /** @noinspection PhpUnhandledExceptionInspection Will never be thrown as we have checked above */
    $vaultConfig = $config->get('vault');

    // Phinx only handles SQL migrations. Non-SQL named-vaults
    // (e.g. apexl/vault 3.1.0+ ships a mongodb driver — see TC's
    // plans/vault-mongo.md) carry a different connection-config
    // shape (uri/database instead of dbhost/dbname/etc) and run
    // their migrations via a separate path. Skip them here rather
    // than emitting 5 PHP warnings per entry per request when
    // ConfigurationFactory loads this file at web-bootstrap time.
    $sqlAdapters = ['mysql', 'sqlite', 'pgsql', 'sqlsrv'];
    foreach (($vaultConfig['databases'] ?? []) as $name => $connection) {
        $driver = $connection['driver'] ?? 'mysql';
        if (!in_array($driver, $sqlAdapters, true)) {
            continue;
        }
        $phinxConfig['environments'][$name] = [
            'adapter' => $driver,
            'host'    => $connection['dbhost'] ?? '',
            'name'    => $connection['dbname'] ?? '',
            'user'    => $connection['dbuser'] ?? '',
            'pass'    => $connection['dbpass'] ?? '',
            'port'    => $connection['port']   ?? '',
        ];
    }
}

return $phinxConfig;
