import { NextRequest, NextResponse } from 'next/server';
import { and, eq } from 'drizzle-orm';
import { db, wishlistItems, wishlists, itemClaims } from '@/lib/db';
import { getGuestFromRequest, verifyAdminToken } from '@/lib/auth/tokens';

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const guest = await getGuestFromRequest(request);
    const isAdmin = verifyAdminToken(request);
    if (!guest && !isAdmin) {
      return NextResponse.json({ error: 'Convite necessário' }, { status: 401 });
    }

    const { id } = await params;
    const body = await request.json().catch(() => ({}));

    const targetGuestId = isAdmin && typeof body?.guestId === 'string' ? body.guestId : guest?.id;
    if (!targetGuestId) {
      return NextResponse.json({ error: 'Missing guest' }, { status: 400 });
    }

    const itemRows = await db.select().from(wishlistItems).where(eq(wishlistItems.id, id)).limit(1);
    if (itemRows.length === 0) return NextResponse.json({ error: 'Item not found' }, { status: 404 });

    const wl = await db.select().from(wishlists).where(eq(wishlists.id, itemRows[0].wishlistId)).limit(1);
    if (wl.length === 0) return NextResponse.json({ error: 'Wishlist not found' }, { status: 404 });
    if (!wl[0].isPublic && !isAdmin) {
      return NextResponse.json({ error: 'This wishlist is private' }, { status: 403 });
    }

    const result = await db
      .delete(itemClaims)
      .where(and(eq(itemClaims.itemId, id), eq(itemClaims.guestId, targetGuestId)))
      .returning();

    if (result.length === 0) {
      return NextResponse.json({ error: 'Reserva não encontrada' }, { status: 404 });
    }

    await db.update(wishlistItems).set({ updatedAt: new Date() }).where(eq(wishlistItems.id, id));

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error('Error unclaiming item:', err);
    return NextResponse.json({ error: 'Failed to unclaim item' }, { status: 500 });
  }
}
