import postgres from 'postgres'
import { readdir, readFile } from 'node:fs/promises'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'

const __dirname = dirname(fileURLToPath(import.meta.url))
const sqlDir = join(__dirname, '../../../sql')

const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) {
  console.error('[db-migrate] DATABASE_URL is not set')
  process.exit(1)
}

const sql = postgres(databaseUrl)

await sql`
  CREATE TABLE IF NOT EXISTS schema_migrations (
    filename TEXT PRIMARY KEY,
    applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
  )
`

const applied = new Set((await sql`SELECT filename FROM schema_migrations`).map((r) => r.filename))

const files = (await readdir(sqlDir)).filter((f) => f.endsWith('.sql')).sort()

for (const file of files) {
  if (applied.has(file)) {
    console.log(`[db-migrate] skip ${file} (already applied)`)
    continue
  }
  const content = await readFile(join(sqlDir, file), 'utf8')
  console.log(`[db-migrate] applying ${file}...`)
  await sql.unsafe(content)
  await sql`INSERT INTO schema_migrations (filename) VALUES (${file})`
  console.log(`[db-migrate] applied ${file}`)
}

await sql.end()
console.log('[db-migrate] done')
