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

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

    const { id } = await params;
    const body = await request.json().catch(() => ({}));
    const requestedQty = Math.max(1, Math.floor(Number(body?.quantity ?? 1)));
    const note = (body?.note ?? '').toString().trim() || null;

    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 item = itemRows[0];

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

    // Sum quantities reserved by OTHER guests
    const otherSumRow = await db
      .select({ total: sql<number>`COALESCE(SUM(${itemClaims.quantity}), 0)` })
      .from(itemClaims)
      .where(and(eq(itemClaims.itemId, id), ne(itemClaims.guestId, guest.id)));
    const otherSum = Number(otherSumRow[0]?.total ?? 0);

    if (otherSum + requestedQty > item.quantity) {
      const remaining = Math.max(0, item.quantity - otherSum);
      return NextResponse.json(
        { error: `Apenas ${remaining} disponível(is)`, remaining },
        { status: 409 }
      );
    }

    // Upsert: replace existing claim for this (item, guest)
    const existing = await db
      .select()
      .from(itemClaims)
      .where(and(eq(itemClaims.itemId, id), eq(itemClaims.guestId, guest.id)))
      .limit(1);

    if (existing.length > 0) {
      await db
        .update(itemClaims)
        .set({ quantity: requestedQty, note, updatedAt: new Date() })
        .where(eq(itemClaims.id, existing[0].id));
    } else {
      await db.insert(itemClaims).values({
        itemId: id,
        guestId: guest.id,
        quantity: requestedQty,
        note,
      });
    }

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

    const updated = await fetchItemWithClaims(id);
    return NextResponse.json({ success: true, item: updated }, { status: 201 });
  } catch (err) {
    console.error('Error claiming item:', err);
    return NextResponse.json({ error: 'Failed to claim item' }, { status: 500 });
  }
}

async function fetchItemWithClaims(itemId: string) {
  const itemRows = await db.select().from(wishlistItems).where(eq(wishlistItems.id, itemId)).limit(1);
  if (itemRows.length === 0) return null;
  const claims = await db
    .select({
      id: itemClaims.id,
      quantity: itemClaims.quantity,
      note: itemClaims.note,
      isPurchased: itemClaims.isPurchased,
      claimedAt: itemClaims.claimedAt,
      guestId: guests.id,
      guestName: guests.name,
    })
    .from(itemClaims)
    .innerJoin(guests, eq(itemClaims.guestId, guests.id))
    .where(eq(itemClaims.itemId, itemId));
  const claimedQuantity = claims.reduce((s, c) => s + c.quantity, 0);
  return {
    ...itemRows[0],
    claims: claims.map((c) => ({
      id: c.id,
      quantity: c.quantity,
      note: c.note,
      isPurchased: c.isPurchased,
      claimedAt: c.claimedAt,
      guest: { id: c.guestId, name: c.guestName },
    })),
    claimedQuantity,
    remainingQuantity: Math.max(0, itemRows[0].quantity - claimedQuantity),
  };
}
