import { usePrisma } from "../../utils/prisma";
import { awardPoints } from "../../utils/scoring";

/**
 * POST /api/community/repost
 * Body: { postId: string }
 * Creates a repost referencing the original post.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const { postId } = (await readBody(event)) as { postId: string };

  if (!postId) {
    throw createError({ statusCode: 400, message: "postId erforderlich" });
  }

  const db = usePrisma();

  // Original-Post laden
  const original = await db.communityPost.findUnique({
    where: { id: postId },
    select: { id: true, userId: true, repostOfId: true },
  });

  if (!original) {
    throw createError({ statusCode: 404, message: "Post nicht gefunden" });
  }

  // Nicht den eigenen Post resharen
  if (original.userId === user.id) {
    throw createError({
      statusCode: 400,
      message: "Eigene Posts können nicht geteilt werden",
    });
  }

  // Wenn es selbst ein Repost ist, das Original resharen
  const targetId = original.repostOfId ?? original.id;

  // Prüfen ob User diesen Post schon gerepostet hat
  const existing = await db.communityPost.findFirst({
    where: { userId: user.id, repostOfId: targetId },
  });

  if (existing) {
    throw createError({
      statusCode: 409,
      message: "Du hast diesen Beitrag bereits geteilt",
    });
  }

  // Repost erstellen
  const repost = await db.communityPost.create({
    data: {
      userId: user.id,
      category: "repost",
      content: "",
      repostOfId: targetId,
      isAnonymous: false,
      isModerated: false,
    },
    include: {
      author: {
        select: { id: true, username: true, nickname: true, avatar: true },
      },
    },
  });

  // repostsCount auf Original erhöhen
  await db.communityPost.update({
    where: { id: targetId },
    data: { repostsCount: { increment: 1 } },
  });

  // Punkte für den Original-Autor
  if (original.userId !== user.id) {
    await awardPoints(original.userId, "upvote_received", {
      post_id: targetId,
    }).catch(() => {});
  }

  return repost;
});
