#!/usr/bin/env node
/** Drops the local SQLite database file so `db:reset` can rebuild from scratch. */
import { rmSync, existsSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join, resolve } from 'node:path'
import { readFileSync } from 'node:fs'

const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')

function env(key) {
  if (process.env[key]) return process.env[key]
  for (const file of ['.env.local', '.env']) {
    try {
      const m = readFileSync(join(ROOT, file), 'utf8').match(new RegExp(`^\\s*${key}\\s*=\\s*(.*)$`, 'm'))
      if (m) return m[1].trim().replace(/^["']|["']$/g, '')
    } catch {
      /* file absent */
    }
  }
  return undefined
}

const provider = (env('DATABASE_PROVIDER') || 'sqlite').toLowerCase()

if (provider !== 'sqlite') {
  console.log('[db-reset] provider is not sqlite — use `prisma migrate reset` for PostgreSQL')
  process.exit(0)
}

const url = env('DATABASE_URL') || 'file:./nabdh.db'
const file = resolve(ROOT, 'prisma', url.replace(/^file:/, ''))

for (const path of [file, `${file}-journal`, `${file}-wal`, `${file}-shm`]) {
  if (existsSync(path)) {
    rmSync(path)
    console.log(`[db-reset] removed ${path}`)
  }
}
console.log('[db-reset] done')
