/**
 * Dev-only helper: issue a CRM admin invite and send the activation email.
 * The email gets routed via EMAIL_REDIRECT_TO if that's set, so it always
 * lands in the dev inbox.
 *
 * Run: pnpm tsx scripts/dev-trigger-crm-invite.ts <email> [name] [--super]
 */

import 'dotenv/config';

import { createCrmInvite } from '@/lib/services/crm-invite.service';

async function main() {
  const args = process.argv.slice(2);
  const email = args[0];
  if (!email) {
    console.error('Usage: pnpm tsx scripts/dev-trigger-crm-invite.ts <email> [name] [--super]');
    process.exit(1);
  }
  const isSuperAdmin = args.includes('--super');
  const name = args.find((a, i) => i > 0 && !a.startsWith('--'));

  // Dev script runs out-of-band (no HTTP request, no session). The service's
  // super-admin gate requires `invitedBy.isSuperAdmin === true` for super
  // invites; the script bypasses that with a synthetic caller identity.
  const { inviteId, link } = await createCrmInvite({
    email,
    name,
    isSuperAdmin,
    invitedBy: { userId: 'cli-script', isSuperAdmin: true },
  });
  console.log(`✓ Invite created (id=${inviteId})`);
  console.log(`  email: ${email}`);
  console.log(`  super_admin: ${isSuperAdmin}`);
  console.log(`  activation link: ${link}`);
  console.log('');
  console.log('Email sent (subject permitting via EMAIL_REDIRECT_TO).');
  process.exit(0);
}

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