<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\Config\Environment;
use App\Framework\Database\Config\DatabaseConfigInitializer;
use App\Framework\Database\DatabaseManager;
use App\Framework\Database\Migration\MigrationRunner;
use App\Framework\Database\Platform\DatabasePlatformInitializer;
use App\Framework\DateTime\Clock;
use App\Framework\DateTime\SystemClock;
use App\Framework\DateTime\SystemTimer;
use App\Framework\DI\DefaultContainer;

echo "=== Direct Migration Test ===\n\n";

try {
    // Setup environment with .env file
    $env = Environment::fromFile(__DIR__ . '/../../.env');
    echo "1. Environment loaded from .env\n";

    // Initialize database platform
    $platformInitializer = new DatabasePlatformInitializer($env);
    $platform = $platformInitializer->__invoke();
    echo "2. Database platform initialized: " . $platform->getName() . "\n";

    // Initialize database config
    $dbConfigInitializer = new DatabaseConfigInitializer($env);
    $dbConfig = $dbConfigInitializer->__invoke();
    echo "3. Database config initialized\n";

    // Setup container manually
    $container = new DefaultContainer();
    $container->singleton(Environment::class, $env);
    $container->singleton(\App\Framework\Database\Platform\DatabasePlatform::class, $platform);
    $container->singleton(\App\Framework\Database\Config\DatabaseConfig::class, $dbConfig);
    echo "4. Container setup with platform and config\n";

    // Create timer and clock
    $timer = new SystemTimer();
    $clock = new SystemClock();
    $container->singleton(Clock::class, $clock);

    // Initialize database manager directly
    $databaseManager = new DatabaseManager($dbConfig, $timer, 'database/migrations', $clock);
    $connection = $databaseManager->getConnection();
    $container->singleton(\App\Framework\Database\ConnectionInterface::class, $connection);
    echo "5. Database connection established\n";

    // Test connection
    $pdo = $connection->getPdo();
    echo "6. Testing database connection...\n";
    $result = $pdo->query("SELECT 1 as test")->fetch();
    echo "   Connection test result: " . $result['test'] . "\n";

    // Create migration runner manually
    $migrationRunner = new MigrationRunner(
        connection: $connection,
        platform: $platform,
        clock: $clock
    );
    echo "7. Migration runner created successfully\n";

    // Test migrations table creation
    echo "8. Testing migrations table creation...\n";

    // Check if migrations table exists by running a simple query
    try {
        $sql = $platform->getTableExistsSQL('framework_migrations');
        $result = $connection->queryColumn($sql);
        $exists = ! empty($result) && (int) $result[0] > 0;
        echo "   Migrations table exists: " . ($exists ? 'Yes' : 'No') . "\n";

        if (! $exists) {
            echo "   Creating migrations table...\n";
            // This will trigger the table creation in the constructor
            // The constructor was already called above, so table should be created
        }

    } catch (\Throwable $e) {
        echo "   Error checking migrations table: " . $e->getMessage() . "\n";
    }

    echo "\n=== Migration Test Successful ===\n";

} catch (\Throwable $e) {
    echo "\n❌ Error: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}
