import { execSync } from "node:child_process"
import { randomUUID } from "node:crypto"
import { writeFileSync } from "node:fs"
import { join } from "node:path"
import readline from "node:readline"

function ask(question: string) {
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
  return new Promise<string>((resolve) =>
    rl.question(question, (answer) => {
      rl.close()
      resolve(answer.trim())
    }),
  )
}

function slugify(input: string) {
  return input
    .trim()
    .toLowerCase()
    .replace(/['"]/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
}

function generateMigrationLock() {
  const timestamp = new Date().toISOString()
  const hash = randomUUID()
  const lockContent = `# Migration Lock File
# This file is auto-generated by the migration script.
# It exists to force git conflicts when multiple developers
# create migrations in parallel, preventing incompatible
# migrations from being merged without conflict resolution.
#
# Generated: ${timestamp}
# Hash: ${hash}
# Do not manually edit this file.
`

  const lockPath = join(process.cwd(), "drizzle", ".migration-lock")
  writeFileSync(lockPath, lockContent)
  console.log(`Migration lock updated: ${lockPath}`)
}

async function main() {
  const modeArg = process.argv[2] // "auto" | "custom" | undefined
  const nameArg = process.argv[3] // optional name

  let mode = modeArg
  if (mode !== "auto" && mode !== "custom") {
    const m = await ask("Migration type ([a]uto / [c]ustom): ")
    mode = m.toLowerCase().startsWith("c") ? "custom" : "auto"
  }

  let name = nameArg ?? (await ask("Migration name: "))
  if (!name) {
    console.error("Migration name required")
    process.exit(1)
  }

  name = slugify(name)

  const customFlag = mode === "custom" ? "--custom " : ""
  const cmd = `drizzle-kit generate ${customFlag}--config=drizzle.config.ts --name ${name}`

  execSync(cmd, { stdio: "inherit" })

  // Generate conflict lock file after successful migration generation
  generateMigrationLock()
  console.log("\nMigration generation complete!")
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})
