import { NextRequest, NextResponse } from 'next/server';
import { desc } from 'drizzle-orm';
import { db, guests } from '@/lib/db';
import { verifyAdminToken } from '@/lib/auth/tokens';

export async function GET(request: NextRequest) {
  if (!verifyAdminToken(request)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  const rows = await db.select().from(guests).orderBy(desc(guests.createdAt));
  return NextResponse.json({ success: true, guests: rows });
}

export async function POST(request: NextRequest) {
  if (!verifyAdminToken(request)) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  const body = await request.json().catch(() => ({}));
  const name = (body?.name ?? '').toString().trim();
  if (!name) {
    return NextResponse.json({ error: 'name is required' }, { status: 400 });
  }
  const [row] = await db.insert(guests).values({ name }).returning();
  return NextResponse.json({ success: true, guest: row }, { status: 201 });
}
