import { NextRequest, NextResponse } from 'next/server';
import { desc, eq } from 'drizzle-orm';
import { db, itemClaims, wishlistItems, wishlists, 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({
      claimId: itemClaims.id,
      quantity: itemClaims.quantity,
      note: itemClaims.note,
      isPurchased: itemClaims.isPurchased,
      claimedAt: itemClaims.claimedAt,
      itemId: wishlistItems.id,
      itemName: wishlistItems.name,
      itemQuantity: wishlistItems.quantity,
      wishlistSlug: wishlists.slug,
      wishlistName: wishlists.name,
      guestId: guests.id,
      guestName: guests.name,
    })
    .from(itemClaims)
    .innerJoin(wishlistItems, eq(itemClaims.itemId, wishlistItems.id))
    .innerJoin(wishlists, eq(wishlistItems.wishlistId, wishlists.id))
    .innerJoin(guests, eq(itemClaims.guestId, guests.id))
    .orderBy(desc(itemClaims.claimedAt));

  return NextResponse.json({ success: true, claims: rows });
}
