import { NextResponse } from "next/server";
import { listSanityProductsByHandles } from "@/lib/sanity/queries";

const MAX_HANDLES = 100;

export async function POST(request: Request) {
  let handles: unknown;

  try {
    const body = await request.json();
    handles = body?.handles;
  } catch {
    return NextResponse.json({ error: "invalid_body" }, { status: 400 });
  }

  if (!Array.isArray(handles) || !handles.every((handle) => typeof handle === "string")) {
    return NextResponse.json({ error: "invalid_handles" }, { status: 400 });
  }

  const products = await listSanityProductsByHandles(handles.slice(0, MAX_HANDLES));

  return NextResponse.json({ products });
}
