<?php
/**
 * Phinx 数据库迁移配置
 * 与 Webman ThinkOrm 引导一致：Config 加载后合并 thinkorm + think-orm，供 phinx migrate 使用
 */
declare(strict_types=1);

$baseDir = __DIR__;

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

if (class_exists('Dotenv\Dotenv') && is_file($baseDir . '/.env')) {
    // 必须用 Mutable：Webman Worker 已加载过时，Immutable 不会覆盖 $_ENV，会导致 Phinx 与 Db::name() 前缀/库名不一致
    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;
    }
}

if (!defined('BASE_PATH')) {
    define('BASE_PATH', $baseDir);
}

require $baseDir . '/vendor/workerman/webman-framework/src/support/helpers.php';
require $baseDir . '/app/functions.php';

use Webman\Config;

Config::clear();
Config::load($baseDir . '/config', ['route', 'middleware', 'process', 'server', 'static']);
$thinkorm = array_replace_recursive(config('thinkorm', []), config('think-orm', []));
$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,
        ],
    ],
];
