#!/usr/bin/env tsx
import { eq } from 'drizzle-orm';
import { db, guests, initializeDatabase } from '../lib/db';

function arg(name: string): string | undefined {
  const idx = process.argv.findIndex((a) => a === `--${name}` || a.startsWith(`--${name}=`));
  if (idx < 0) return undefined;
  const a = process.argv[idx];
  if (a.includes('=')) return a.split('=')[1];
  return process.argv[idx + 1];
}

async function main() {
  await initializeDatabase();
  const cmd = process.argv[2];

  if (cmd === 'create') {
    const name = (arg('name') ?? '').trim() || 'Convidado';
    const [row] = await db.insert(guests).values({ name }).returning();
    const base = process.env.PUBLIC_BASE_URL ?? 'http://localhost:3000';
    console.log(JSON.stringify({ id: row.id, name: row.name, link: `${base}/?usr=${row.id}` }, null, 2));
    return;
  }

  if (cmd === 'list') {
    const rows = await db.select().from(guests);
    console.log(JSON.stringify(rows, null, 2));
    return;
  }

  if (cmd === 'delete') {
    const id = arg('id');
    if (!id) { console.error('--id is required'); process.exit(1); }
    const out = await db.delete(guests).where(eq(guests.id, id)).returning();
    if (out.length === 0) { console.error('not found'); process.exit(1); }
    console.log('deleted');
    return;
  }

  console.error('usage: guest <create --name=NAME | list | delete --id=ID>');
  process.exit(1);
}

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