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

const schema = z.object({ reason: z.string().min(1) });

export async function POST(req: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  const body = await req.json().catch(() => ({}));
  const parsed = schema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });

  const report = await prisma.report.create({
    data: { targetType: "POST", postId: id, reason: parsed.data.reason },
  });

  await prisma.postStat.upsert({
    where: { postId: id },
    update: { reportCount: { increment: 1 } },
    create: { postId: id, reportCount: 1 },
  });

  await prisma.adminNotification.create({
    data: { type: "REPORT", message: `신고 발생: post ${id}`, targetType: "POST", targetId: id },
  });

  // 자동 블라인드 임계치: 신고 3회 이상시 hidden 처리
  const stat = await prisma.postStat.upsert({
    where: { postId: id },
    update: { reportCount: { increment: 1 } },
    create: { postId: id, reportCount: 1 },
  });
  const threshold = 3;
  if ((stat.reportCount + 1) >= threshold) {
    await prisma.post.update({ where: { id }, data: { status: "hidden" } });
    await prisma.adminNotification.create({
      data: { type: "AUTO_HIDE", message: `신고 누적 ${threshold}건으로 블라인드됨: post ${id}`, targetType: "POST", targetId: id },
    });
  }

  return NextResponse.json({ ok: true, reportId: report.id });
}


