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 data: any = {};
  for (const k of ["name", "category", "latitude", "longitude", "address", "imageUrl", "sortOrder"]) {
    if (k in body) data[k] = body[k];
  }
  if (typeof data.latitude !== "undefined") data.latitude = Number(data.latitude);
  if (typeof data.longitude !== "undefined") data.longitude = Number(data.longitude);
  if (typeof data.sortOrder !== "undefined") data.sortOrder = Number(data.sortOrder);
  try {
    const partner = await prisma.partner.update({ where: { id }, data });
    return NextResponse.json({ partner });
  } catch (e) {
    // DB에 sortOrder 컬럼이 아직 없는 환경 대비: 해당 키 제거 후 재시도
    if (Object.prototype.hasOwnProperty.call(data, "sortOrder")) {
      const { sortOrder, ...rest } = data;
      const partner = await prisma.partner.update({ where: { id }, data: rest });
      return NextResponse.json({ partner });
    }
    throw e;
  }
}

export async function DELETE(_: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  await prisma.partner.delete({ where: { id } });
  return NextResponse.json({ ok: true });
}


