#!/usr/bin/env node
// ─────────────────────────────────────────────────────────────
// bin/invite.js — add / remove / list invites.
//
// Usage:
//   npm run invite -- add someone@example.com [FirstName]
//   npm run invite -- remove someone@example.com
//   npm run invite -- list
//
// Or directly:
//   node bin/invite.js add someone@example.com Erik
//   node bin/invite.js add someone@example.com    (no name — stored as NULL)
//
// The first name is optional. When present it's used on the welcome
// screen ("Thanks for your interest, Erik."). When absent the welcome
// screen falls back to anonymous copy ("Thank you for your interest.").
// Re-running `add` on an existing email updates the first name only;
// invited_at and invited_by are preserved.
// ─────────────────────────────────────────────────────────────
import { q } from '../src/db.js';

const [, , cmd, emailArg, nameArg] = process.argv;
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

function help() {
  console.log('Usage:');
  console.log('  invite add <email> [FirstName]');
  console.log('  invite remove <email>');
  console.log('  invite list');
  process.exit(1);
}

switch (cmd) {
  case 'add': {
    if (!emailArg || !EMAIL_RE.test(emailArg)) help();
    const email = emailArg.trim().toLowerCase();
    const firstName = nameArg ? nameArg.trim() : null;
    q.upsertInvite.run(email, firstName, Date.now(), 'cli');
    if (firstName) {
      console.log(`Invited ${email} (${firstName})`);
    } else {
      console.log(`Invited ${email}`);
    }
    break;
  }
  case 'remove': {
    if (!emailArg || !EMAIL_RE.test(emailArg)) help();
    const email = emailArg.trim().toLowerCase();
    const result = q.deleteInvite.run(email);
    console.log(result.changes > 0 ? `Removed ${email}` : `No invite for ${email}`);
    break;
  }
  case 'list': {
    const rows = q.listInvites.all();
    if (rows.length === 0) {
      console.log('(no invites)');
    } else {
      for (const r of rows) {
        const d = new Date(r.invited_at).toISOString().slice(0, 10);
        const name = r.first_name ? `  [${r.first_name}]` : '';
        const by = r.invited_by ? `  (by ${r.invited_by})` : '';
        console.log(`  ${d}  ${r.email}${name}${by}`);
      }
      console.log(`\n${rows.length} invite${rows.length === 1 ? '' : 's'} total.`);
    }
    break;
  }
  default:
    help();
}
