<?php

declare(strict_types=1);

/**
 * Database migration + seed runner (CLI).
 *
 * Usage:
 *   php bin/migrate.php            Run pending migrations, then seed.
 *   php bin/migrate.php --fresh    Drop all tables, re-run everything, then seed.
 *   php bin/migrate.php --seed     Run seeds only.
 *
 * Migrations are plain .sql files in database/migrations, applied in filename
 * order. Applied files are recorded in the `migrations` table so re-runs are
 * incremental and safe.
 */

use BotGuard\Core\Config;
use BotGuard\Core\Database;
use BotGuard\Core\Migrator;
use BotGuard\Database\Seeds\DatabaseSeeder;

$basePath = dirname(__DIR__);

$composer = $basePath . '/vendor/autoload.php';
if (is_file($composer)) {
    require $composer;
} else {
    require $basePath . '/app/Core/Autoloader.php';
    BotGuard\Core\Autoloader::register();
}

Config::boot($basePath);

$args = array_slice($argv, 1);
$fresh = in_array('--fresh', $args, true);
$seedOnly = in_array('--seed', $args, true);

$db = Database::fromConfig();

try {
    $db->pdo(); // force connection early for a clear error message
} catch (Throwable $e) {
    fwrite(STDERR, "\n[✗] Cannot connect to the database.\n    " . $e->getMessage() . "\n");
    fwrite(STDERR, "    Check your .env DB_* settings and that MySQL is running.\n\n");
    exit(1);
}

echo "\nBotGuard — database migrator\n";
echo "  Database: " . config('database.database') . " @ " . config('database.host') . "\n\n";

$migrator = new Migrator($db, $basePath . '/database/migrations');

if ($fresh) {
    $migrator->dropAll((string) config('database.database'));
    echo "  • Dropped all existing tables (--fresh)\n";
}

if (! $seedOnly) {
    echo "Migrations:\n";
    $ran = $migrator->run();
    if ($ran === []) {
        echo "  • Nothing to migrate (up to date)\n";
    } else {
        foreach ($ran as $name) {
            echo "  • Applied {$name}\n";
        }
    }
}

echo "\nSeeding:\n";
(new DatabaseSeeder($db))->run();

echo "\n[✓] Done.\n\n";
exit(0);
