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

const createCommentSchema = z.object({
  postId: z.string().min(1),
  authorId: z.string().optional(),
  content: z.string().min(1),
  isAnonymous: z.boolean().optional(),
  isSecret: z.boolean().optional(),
  secretPassword: z.string().min(1).optional(), // 비회원 비밀번호(옵션)
});

export async function POST(req: Request) {
  const body = await req.json();
  const parsed = createCommentSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  }
  const { postId, authorId, content, isAnonymous, isSecret, secretPassword } = parsed.data;
  const secretPasswordHash = secretPassword ? hashPassword(secretPassword) : null;
  const comment = await prisma.comment.create({
    data: {
      postId,
      authorId: authorId ?? null,
      content,
      isAnonymous: !!isAnonymous,
      isSecret: !!isSecret,
      secretPasswordHash,
    },
  });
  return NextResponse.json({ comment }, { status: 201 });
}


