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

export async function PUT(req: Request) {
  const userId = await getUserIdOrAdmin(req);
  if (!userId) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  try {
    const body = await req.json();
    const url: string | null = body?.url ?? null;
    if (url !== null && typeof url !== "string") {
      return NextResponse.json({ error: "invalid url" }, { status: 400 });
    }
    // 간단 검증: 내부 업로드 경로 또는 http(s) 허용
    if (url) {
      const ok = url.startsWith("/uploads/") || url.startsWith("http://") || url.startsWith("https://");
      if (!ok) return NextResponse.json({ error: "invalid url" }, { status: 400 });
      if (url.length > 1000) return NextResponse.json({ error: "url too long" }, { status: 400 });
    }
    const user = await prisma.user.update({
      where: { userId },
      data: { profileImage: url || null },
      select: { userId: true, profileImage: true },
    });
    return NextResponse.json({ ok: true, user });
  } catch {
    return NextResponse.json({ error: "Bad Request" }, { status: 400 });
  }
}


