import fs from 'node:fs'
import path from 'node:path'

const dir='backend/Database/Migrations'
const errors=[]
const destructive=/\b(?:drop\s+(?:table|column|schema|index|constraint)|truncate\s+(?:table\s+)?|alter\s+table[\s\S]{0,120}?\bdrop\b)\b/i
const approval=/KBX-DESTRUCTIVE-MIGRATION-APPROVED:\s*\S+/i
for(const name of fs.readdirSync(dir).filter(x=>x.endsWith('.sql')).sort()){
  const p=path.join(dir,name),text=fs.readFileSync(p,'utf8')
  if(destructive.test(text)&&!approval.test(text))errors.push(`destructive migration requires explicit approval marker + migration guide: ${name}`)
}
const config=JSON.parse(fs.readFileSync('contracts/configuration/kbx.configuration.json','utf8'))
const prod=config.environments.find(x=>x.id==='Production')
if(prod?.migrationStrategy!=='predeploy')errors.push('Production migration strategy must remain predeploy')
if(errors.length){console.error('migration safety FAIL');for(const e of errors)console.error(`- ${e}`);process.exit(1)}
console.log(`migration safety PASS: ${fs.readdirSync(dir).filter(x=>x.endsWith('.sql')).length} migrations, destructive operations guarded`)
