import { NextResponse } from "next/server";
import { addWishlistItem, applyWishlistCookie } from "@/lib/storefront-wishlist";
import type { StorefrontWishlistItem } from "@/types/storefront";

function isWishlistItemBody(value: unknown): value is StorefrontWishlistItem {
  if (!value || typeof value !== "object") {
    return false;
  }

  const item = value as StorefrontWishlistItem;

  return (
    Number.isInteger(item.id) &&
    (typeof item.productId === "undefined" || Number.isInteger(item.productId)) &&
    (typeof item.variationId === "undefined" || Number.isInteger(item.variationId)) &&
    typeof item.slug === "string" &&
    typeof item.type === "string" &&
    typeof item.name === "string" &&
    typeof item.href === "string" &&
    typeof item.label === "string" &&
    typeof item.price === "string"
  );
}

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as unknown;

    if (!isWishlistItemBody(body)) {
      return NextResponse.json(
        { message: "Neispravan proizvod za listu želja." },
        { status: 400 },
      );
    }

    const wishlist = await addWishlistItem(body);
    const response = NextResponse.json(wishlist, { status: 201 });

    applyWishlistCookie(response, wishlist);

    return response;
  } catch (error) {
    return NextResponse.json(
      {
        message:
          error instanceof Error
            ? error.message
            : "Dodavanje u listu želja nije uspjelo.",
      },
      { status: 500 },
    );
  }
}
