<?php
declare(strict_types=1);
require __DIR__ . '/../lib/bootstrap.php';

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

$pdo = db();
$pdo->exec('CREATE TABLE IF NOT EXISTS schema_migrations (migration VARCHAR(255) PRIMARY KEY, applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$applied = array_flip($pdo->query('SELECT migration FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
$deviceIdTypeStmt = $pdo->prepare(
    'SELECT COLUMN_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?'
);
$deviceIdTypeStmt->execute(['devices', 'id']);
$deviceIdType = (string) ($deviceIdTypeStmt->fetchColumn() ?: 'INT UNSIGNED');
$files = glob(__DIR__ . '/../migrations/*.sql') ?: [];
sort($files);

foreach ($files as $file) {
    $name = basename($file);
    if (isset($applied[$name])) {
        echo "skip {$name}\n";
        continue;
    }
    $sql = str_replace('{{DEVICE_ID_TYPE}}', $deviceIdType, trim((string) file_get_contents($file)));
    try {
        foreach (array_filter(array_map('trim', preg_split('/;\s*(?:\r?\n|$)/', $sql))) as $statement) {
            try {
                $pdo->exec($statement);
            } catch (PDOException $error) {
                $mysqlCode = (int) ($error->errorInfo[1] ?? 0);
                if (!in_array($mysqlCode, [1050, 1060, 1061, 1022], true)) {
                    throw $error;
                }
                echo "already present in {$name}: {$mysqlCode}\n";
            }
        }
        $pdo->prepare('INSERT INTO schema_migrations (migration) VALUES (?)')->execute([$name]);
        echo "applied {$name}\n";
    } catch (Throwable $error) {
        fwrite(STDERR, "failed {$name}: {$error->getMessage()}\n");
        exit(1);
    }
}
