import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getRoomByCode, requireMembership } from "@/lib/blindbox";
import { apiHandler, ApiError, requireUserId } from "@/lib/api";

export const GET = apiHandler(async (_req, { params }) => {
  const { code } = await params;
  const room = await getRoomByCode(code.toUpperCase());

  if (!room) throw new ApiError("房间不存在", 404);

  return NextResponse.json({
    id: room.id,
    code: room.code,
    name: room.name,
    creatorId: room.creatorId,
    city: room.city,
    lat: room.lat,
    lng: room.lng,
    poolCount: room._count.ideas,
    members: room.members.map((m) => ({
      ...m.user,
      joinedAt: m.joinedAt,
    })),
  });
});

export const PATCH = apiHandler(async (req, { params }) => {
  const { code } = await params;
  const { userId, city, lat, lng } = await req.json();

  requireUserId(userId);

  const room = await prisma.blindBoxRoom.findUnique({
    where: { code: code.toUpperCase() },
  });
  if (!room) throw new ApiError("房间不存在", 404);

  await requireMembership(room.id, userId);

  const numLat = Number(lat);
  const numLng = Number(lng);
  if (
    !Number.isFinite(numLat) || !Number.isFinite(numLng) ||
    numLat < -90 || numLat > 90 || numLng < -180 || numLng > 180
  ) {
    throw new ApiError("位置坐标无效");
  }

  const updated = await prisma.blindBoxRoom.update({
    where: { id: room.id },
    data: {
      city: typeof city === "string" ? city.trim() : null,
      lat: numLat,
      lng: numLng,
    },
  });

  return NextResponse.json({
    city: updated.city,
    lat: updated.lat,
    lng: updated.lng,
  });
});

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

  requireUserId(userId);

  const room = await prisma.blindBoxRoom.findUnique({
    where: { code: code.toUpperCase() },
  });
  if (!room) throw new ApiError("房间不存在", 404);

  if (room.creatorId === userId) {
    await prisma.blindBoxRoom.delete({ where: { id: room.id } });
    return NextResponse.json({ action: "deleted" });
  }

  const membership = await prisma.blindBoxMember.findUnique({
    where: { roomId_userId: { roomId: room.id, userId } },
  });
  if (!membership) throw new ApiError("你不是该房间成员", 403);

  await prisma.blindBoxMember.delete({ where: { id: membership.id } });
  return NextResponse.json({ action: "left" });
});
