import { NextResponse } from "next/server";
import { getSessionCustomer } from "../../../lib/customerAuth";
import { getWishlist, toggleWishlistItem } from "../../../lib/customerAuth";

export async function GET() {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ items: [] }, { status: 401 });
  const items = await getWishlist(session.token, session.customer.id);
  return NextResponse.json({ items });
}

export async function POST(request: Request) {
  const session = await getSessionCustomer();
  if (!session) return NextResponse.json({ ok: false, reason: "Bitte zuerst einloggen." }, { status: 401 });

  const body = await request.json().catch(() => null);
  const productId = Number(body?.productId);
  const variant = typeof body?.variant === "string" ? body.variant : "";
  if (!Number.isInteger(productId) || productId <= 0) {
    return NextResponse.json({ ok: false, reason: "Ungültiges Produkt." }, { status: 400 });
  }

  const result = await toggleWishlistItem(session.token, session.customer.id, productId, variant);
  if (!result.ok) return NextResponse.json({ ok: false, reason: "Merkliste konnte nicht aktualisiert werden." }, { status: 500 });
  return NextResponse.json({ ok: true, wishlisted: result.wishlisted });
}
