import { getPostById, getPostLike } from "../../../db/community";
import { getFollowRelation } from "../../../db/social";
import { usePrisma } from "../../../utils/prisma";

/** GET /api/community/[postId] */
export default defineEventHandler(async (event) => {
  const postId = getRouterParam(event, "postId");
  if (!postId) throw createError({ statusCode: 400, message: "postId fehlt" });

  const config = useRuntimeConfig();
  const lyraBotUserId = config.lyraBotUserId || null;
  const rebreakBotUserId = config.rebreakBotUserId || null;

  // Auth-User optional
  let currentUserId: string | null = null;
  try {
    const u = await requireUser(event);
    currentUserId = u.id;
  } catch {}

  const db = usePrisma();
  const [data, likeRow] = await Promise.all([
    getPostById(postId),
    currentUserId ? getPostLike(currentUserId, postId) : Promise.resolve(null),
  ]);

  if (!data || data.isModerated) {
    throw createError({ statusCode: 404, message: "Post nicht gefunden" });
  }

  const [followRow, scoreRow] = await Promise.all([
    currentUserId && data.userId && currentUserId !== data.userId
      ? getFollowRelation(currentUserId, data.userId)
      : Promise.resolve(null),
    data.userId
      ? db.userScore.findUnique({
          where: { userId: data.userId },
          select: { tier: true },
        })
      : Promise.resolve(null),
  ]);

  const challengeId = (data as any).challengeId ?? null;
  const challengeRow = challengeId
    ? await db.gameChallenge.findUnique({
        where: { id: challengeId },
        select: {
          gameType: true,
          isLive: true,
          opponentName: true,
          status: true,
        },
      })
    : null;

  const a = data.author;
  const isGameShare = data.category === "game_share";
  return {
    id: data.id,
    category: data.category,
    content: isGameShare
      ? data.content.split("\n").slice(1).join("\n").trim()
      : data.content,
    imageUrl: (data as any).imageUrl ?? null,
    challengeId,
    challengeStatus: (challengeRow as any)?.status ?? null,
    gameName: challengeId
      ? (challengeRow as any)?.gameType ?? null
      : isGameShare
        ? data.content.split("\n")[0] ?? null
        : null,
    opponentName: (challengeRow as any)?.opponentName ?? null,
    isLive: (challengeRow as any)?.isLive ?? false,
    likesCount: data.likesCount ?? 0,
    dislikesCount: data.dislikesCount ?? 0,
    commentsCount: data.commentsCount ?? 0,
    repostsCount: (data as any).repostsCount ?? 0,
    isAnonymous: data.isAnonymous,
    createdAt: data.createdAt,
    userLike: (likeRow?.type as "like" | "dislike") ?? null,
    repostOfId: null,
    repostOf: null,
    author: {
      id: data.userId ?? null,
      username: a?.username ?? "Anonym",
      nickname: a?.nickname ?? a?.username ?? "Anonym",
      avatar: a?.avatar ?? null,
      plan: (a as any)?.plan ?? "free",
      tier: scoreRow?.tier ?? "beginner",
      isFollowing: !!followRow,
    },
    isBot:
      !!(lyraBotUserId && data.userId === lyraBotUserId) ||
      !!(rebreakBotUserId && data.userId === rebreakBotUserId),
    botType:
      lyraBotUserId && data.userId === lyraBotUserId
        ? "lyra"
        : rebreakBotUserId && data.userId === rebreakBotUserId
          ? "rebreak"
          : undefined,
  };
});
