// One-off bootstrap script — inserts (or reactivates) a PlatformAdmin row so
// the vendor-side `/platform/login` console can be reached. The `PlatformAdmin`
// table has no seeded rows by default, so a fresh production database leaves
// nobody able to log in until this is run once.
//
// Usage:
//   PLATFORM_ADMIN_EMAIL=name@company.com \
//   PLATFORM_ADMIN_NAME="Display Name" \
//     npx ts-node -r dotenv/config src/scripts/bootstrap-platform-admin.ts
//
//   # or as argv:
//   npx ts-node -r dotenv/config src/scripts/bootstrap-platform-admin.ts name@company.com "Display Name"
//
// Idempotent — re-running with the same email reactivates the row (sets
// isActive = true) without creating a duplicate.

import { prisma } from '../config/database';

async function main(): Promise<void> {
  const rawEmail = process.env.PLATFORM_ADMIN_EMAIL || process.argv[2];
  const name = process.env.PLATFORM_ADMIN_NAME || process.argv[3] || null;

  if (!rawEmail || !rawEmail.includes('@')) {
    console.error('Missing email. Pass PLATFORM_ADMIN_EMAIL=... or as the first argument.');
    process.exit(1);
  }

  const email = rawEmail.trim().toLowerCase();

  const row = await prisma.platformAdmin.upsert({
    where: { email },
    create: { email, name, isActive: true },
    update: { isActive: true, ...(name ? { name } : {}) },
  });

  console.log(`✓ Platform admin ready: ${row.email} (id=${row.id}, active=${row.isActive})`);
}

main()
  .catch((e) => {
    console.error('bootstrap-platform-admin failed:', e);
    process.exit(1);
  })
  .finally(() => prisma.$disconnect());
