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

const schema = z.object({ userId: z.string().optional(), clientHash: z.string().optional() }).refine(
  (d) => !!d.userId || !!d.clientHash,
  { message: "Provide userId or clientHash" }
);

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 { userId, clientHash } = parsed.data;

  const existing = await prisma.reaction.findFirst({
    where: { postId: id, type: "RECOMMEND", userId: userId ?? null, clientHash: clientHash ?? null },
    select: { id: true },
  });
  if (!existing) {
    await prisma.reaction.create({ data: { postId: id, type: "RECOMMEND", userId: userId ?? null, clientHash: clientHash ?? null } });
    await prisma.postStat.upsert({
      where: { postId: id },
      update: { recommendCount: { increment: 1 } },
      create: { postId: id, recommendCount: 1 },
    });
  }

  return NextResponse.json({ ok: true });
}


