// Verifies migration 0016 (saved contacts accept role 'dispatcher') against
// the live database using the service-role key from .env: inserts one probe
// row for a throwaway owner id and deletes it again. Safe to re-run.
import { createClient } from '@supabase/supabase-js'
import { readFileSync } from 'node:fs'

const env = Object.fromEntries(
  readFileSync('.env', 'utf8')
    .split('\n')
    .filter((l) => l && !l.startsWith('#') && l.includes('='))
    .map((l) => { const i = l.indexOf('='); return [l.slice(0, i).trim(), l.slice(i + 1).trim().replace(/^'(.*)'$/s, '$1')] }),
)
const admin = createClient(env.NEXT_PUBLIC_SUPABASE_URL, env.SUPABASE_SERVICE_ROLE_KEY, { auth: { persistSession: false } })
// The probe needs a REAL owner: carrier_contacts.owner_id references profiles,
// so a made-up id fails on the foreign key (code 23503) — not on the role
// check (23514) this script is about. (2026-09-15: a fake owner made the
// script report NOT APPLIED after Nash had applied the migration.)
const { data: anyProfile } = await admin.from('profiles').select('id').limit(1).maybeSingle()
if (!anyProfile) {
  console.log('ERROR — no profile row exists to own the probe contact')
  process.exit(1)
}
const { data, error } = await admin
  .from('carrier_contacts')
  .insert({ owner_id: anyProfile.id, name: 'Migration 0016 probe', email: 'probe-0016@example.invalid', phone: '000-000-0000', role: 'dispatcher' })
  .select('id')
  .single()
if (error) {
  const roleCheck = error.code === '23514' || /carrier_contacts_role_check/i.test(error.message)
  console.log(roleCheck ? 'NOT APPLIED — role check still rejects dispatcher' : `ERROR — ${error.message}`)
  process.exit(1)
}
await admin.from('carrier_contacts').delete().eq('id', data.id)
console.log('APPLIED — dispatcher contacts accepted (probe row removed)')
