import { NextResponse } from "next/server";
import prisma from "@/lib/prisma";

export async function PATCH(req: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  const body = await req.json().catch(() => ({}));
  const roles = Array.isArray(body?.roles) ? (body.roles as string[]) : [];
  const all = await prisma.role.findMany({ select: { roleId: true, name: true } });
  const wanted = new Set(roles);
  // 현재 매핑
  const existing = await prisma.userRole.findMany({ where: { userId: id } });
  const toKeep = new Set(
    existing.filter((ur) => all.find((r) => r.roleId === ur.roleId && wanted.has(r.name))).map((ur) => ur.roleId)
  );
  // 삭제
  await prisma.userRole.deleteMany({ where: { userId: id, roleId: { notIn: Array.from(toKeep) } } });
  // 추가
  for (const r of all) {
    if (wanted.has(r.name) && !toKeep.has(r.roleId)) {
      await prisma.userRole.create({ data: { userId: id, roleId: r.roleId } });
    }
  }
  return NextResponse.json({ ok: true });
}


