<?php
/**
 * Phinx 数据库迁移配置
 * 从 config/thinkorm.php 读取数据库连接，用于 php vendor/bin/phinx migrate
 */
declare(strict_types=1);

$baseDir = __DIR__;

require $baseDir . '/vendor/autoload.php';

if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) {
    if (method_exists('Dotenv\Dotenv', 'createUnsafeImmutable')) {
        Dotenv\Dotenv::createUnsafeImmutable($baseDir)->load();
    } else {
        Dotenv\Dotenv::createMutable($baseDir)->load();
    }
}

if (!function_exists('env')) {
    function env(string $key, mixed $default = null): mixed
    {
        $value = $_ENV[$key] ?? getenv($key);
        if ($value !== false && $value !== null) {
            return $value;
        }
        if (strpos($key, '.') !== false) {
            $parts = explode('.', $key);
            $upper = strtoupper(implode('_', $parts));
            $value = $_ENV[$upper] ?? getenv($upper);
            if ($value !== false && $value !== null) {
                return $value;
            }
        }
        return $default;
    }
}

$thinkorm = require $baseDir . '/config/thinkorm.php';
$conn = $thinkorm['connections'][$thinkorm['default'] ?? 'mysql'] ?? [];
$prefix = $conn['prefix'] ?? '';

return [
    'paths' => [
        'migrations' => $baseDir . '/database/migrations',
        'seeds'      => $baseDir . '/database/seeds',
        'bootstrap'  => $baseDir . '/phinx-bootstrap.php',
    ],
    'environments' => [
        'default_migration_table' => $prefix . 'phinxlog',
        'default_environment'      => 'prod',
        'prod' => [
            'adapter'       => 'mysql',
            'host'          => $conn['hostname'] ?? '127.0.0.1',
            'name'          => $conn['database'] ?? '',
            'user'          => $conn['username'] ?? 'root',
            'pass'          => $conn['password'] ?? '',
            'port'          => $conn['hostport'] ?? 3306,
            'charset'       => $conn['charset'] ?? 'utf8mb4',
            'table_prefix'  => $prefix,
        ],
    ],
];
