#!/usr/bin/env node
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import { executeEnvelope, failExecute, printEnvelope } from '../../../../../lib/output.js'

const COMMAND = 'scaffold-migration'

async function main(): Promise<void> {
  const { values } = parseArgs({ options: { spec: { type: 'string' } }, strict: true })
  if (!values.spec) { printEnvelope(failExecute(COMMAND, ['--spec is required'])); process.exit(1) }
  let raw: unknown
  try { raw = JSON.parse(values.spec) } catch { printEnvelope(failExecute(COMMAND, ['Invalid JSON'])); process.exit(1) }
  const v = validate(raw)
  if (!v.valid) { printEnvelope(failExecute(COMMAND, v.errors)); process.exit(1) }
  const r = await execute(raw as any)
  if (r.success) {
    printEnvelope(executeEnvelope(COMMAND, { report: { output: r.output, sqlObjectsInlined: r.sqlObjectsInlined }, nextSteps: ['Run dotnet build'] }))
  } else {
    printEnvelope({ ...failExecute(COMMAND, ['Migration failed']), report: { output: r.output }, nextSteps: ['Fix errors and retry'] })
  }
  process.exit(r.success ? 0 : 1)
}

void main()
