import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { apiHandler, ApiError, requireUserId, requireUser } from "@/lib/api";

export const GET = apiHandler(async (req) => {
  const userId = req.nextUrl.searchParams.get("userId");
  if (!userId) return NextResponse.json([]);

  const favorites = await prisma.favorite.findMany({
    where: { userId },
    orderBy: { createdAt: "desc" },
    take: 50,
  });

  return NextResponse.json(
    favorites.map((f) => {
      let restaurantData = {};
      try { restaurantData = JSON.parse(f.restaurantData); } catch { /* ignore */ }
      return { id: f.id, restaurantData, createdAt: f.createdAt.toISOString() };
    }),
  );
});

export const POST = apiHandler(async (req) => {
  const { userId, restaurant } = await req.json();

  requireUserId(userId);
  if (!restaurant?.id || typeof restaurant.id !== "string") {
    throw new ApiError("缺少必要字段");
  }

  await requireUser(userId);

  try {
    const fav = await prisma.favorite.create({
      data: {
        userId,
        restaurantId: restaurant.id,
        restaurantData: JSON.stringify(restaurant),
      },
    });
    return NextResponse.json({ id: fav.id });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2002") {
      const existing = await prisma.favorite.findFirst({
        where: { userId, restaurantId: restaurant.id },
      });
      return NextResponse.json({ id: existing?.id ?? "", alreadyExists: true });
    }
    throw e;
  }
});

export const DELETE = apiHandler(async (req) => {
  const { userId, favoriteId } = await req.json();

  requireUserId(userId);
  if (!favoriteId) throw new ApiError("缺少必要字段");

  const fav = await prisma.favorite.findUnique({ where: { id: favoriteId } });
  if (!fav || fav.userId !== userId) throw new ApiError("收藏不存在", 404);

  await prisma.favorite.delete({ where: { id: favoriteId } });
  return NextResponse.json({ ok: true });
});
