import type { MigrationDb } from "./runtime-migration-runner.ts";

/**
 * Self-hosted SQLite files created by the legacy `node:sqlite` runtime already contain the
 * schema produced by migrations/0001~0006.sql. When switching to the Drizzle-managed
 * backend, the Drizzle baseline `drizzle/sqlite/0000_initial.sql` would conflict (tables
 * already exist). This shim detects a legacy database and pre-fills a "0000_initial.sql"
 * row into `runtime_migrations` so the baseline migration is skipped while future
 * migrations (0001_*, 0002_*, etc.) still run normally.
 */
export async function adoptLegacySqliteMigrations(db: MigrationDb): Promise<void> {
  const migrationsTable = await db
    .prepare("select name from sqlite_master where type = 'table' and name = 'runtime_migrations'")
    .get();
  if (!migrationsTable) {
    return;
  }

  const legacyRows = await db.prepare("select name from runtime_migrations where name glob '000[1-6]_*.sql'").all();
  if (legacyRows.length === 0) {
    return;
  }

  const idColumn = await db.prepare("select name from pragma_table_info('connections') where name = 'id'").get();
  if (!idColumn) {
    return;
  }

  const baseline = await db.prepare("select name from runtime_migrations where name = '0000_initial.sql'").get();
  if (baseline) {
    return;
  }

  await db
    .prepare("insert into runtime_migrations (name, applied_at) values (?, ?)")
    .run("0000_initial.sql", new Date().toISOString());
}
