<?php
declare(strict_types=1);

$host = getenv('DB_HOST') ?: 'db';
$username = getenv('DB_SETUP_USERNAME') ?: getenv('DB_USERNAME') ?: 'root';
$password = getenv('DB_SETUP_PASSWORD') ?: getenv('DB_PASSWORD') ?: '';
$charset = getenv('DB_CHARSET') ?: 'utf8mb4';
$schemas = [
    __DIR__ . '/../Leaflet/sql/schema.sql',
    __DIR__ . '/../Leaflet/sql/spatial_schema.sql',
    __DIR__ . '/../Leaflet2/sql/miskin_schema.sql',
];

function connectWithRetry(string $dsn, string $username, string $password): PDO
{
    $lastException = null;

    for ($attempt = 1; $attempt <= 20; $attempt++) {
        try {
            return new PDO($dsn, $username, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
        } catch (PDOException $exception) {
            $lastException = $exception;
            fwrite(STDERR, "Database belum siap, mencoba lagi ({$attempt}/20)...\n");
            sleep(3);
        }
    }

    throw $lastException ?? new RuntimeException('Koneksi database gagal.');
}

try {
    $dsn = "mysql:host={$host};charset={$charset}";
    $pdo = connectWithRetry($dsn, $username, $password);

    foreach ($schemas as $schemaPath) {
        $sql = file_get_contents($schemaPath);
        if ($sql === false) {
            throw new RuntimeException("File schema tidak ditemukan: {$schemaPath}");
        }
        $pdo->exec($sql);
    }

    $pdo->exec("
        GRANT ALL PRIVILEGES ON webgis_spbu.* TO 'webgis_user'@'%';
        GRANT ALL PRIVILEGES ON webgis_miskin.* TO 'webgis_user'@'%';
        FLUSH PRIVILEGES;
    ");

    fwrite(STDOUT, "Database schema siap.\n");
} catch (Throwable $exception) {
    fwrite(STDERR, "Gagal memastikan database schema: " . $exception->getMessage() . "\n");
    exit(1);
}
