#!/usr/bin/env php
<?php
/**
 * Database migration script for Auth Microservice
 * Creates database `emmanylcode_auth` and tables: auth_roles, auth_statuses, auth_users
 * Usage: php migration.php
 */

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

$host = getenv('DB_HOST') ?: '127.0.0.1';
$port = getenv('DB_PORT') ?: 3306;
$user = getenv('DB_USER') ?: 'root';
$pass = getenv('DB_PASS') ?: '';
$dbName = getenv('DB_NAME') ?: 'emmanylcode_auth';

try {
    $pdo = new PDO("mysql:host={$host};port={$port}", $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

    echo "Connected to MySQL server on {$host}:{$port}\n";

    // Create database if not exists
    $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;");
    echo "Database `{$dbName}` ensured.\n";

    // Use database
    $pdo->exec("USE `{$dbName}`;");

    foreach (glob(__DIR__ . '/database/migrations/*.php') as $migration) {
        $runner = require $migration;
        $runner($pdo);
        echo basename($migration) . " applied.\n";
    }

    // Seed roles (if not exists)
    foreach (glob(__DIR__ . '/database/seeders/*.php') as $seeder) {
        $runner = require $seeder;
        $runner($pdo);
        echo basename($seeder) . " seeded.\n";
    }

    echo "Migration completed successfully.\n";

} catch (PDOException $e) {
    echo "Migration failed: " . $e->getMessage() . "\n";
    exit(1);
}

return 0;
