import {
  getFollowRelation,
  createFollow,
  deleteFollow,
  getProfileWithFollowers,
} from "../../db/social";

/**
 * POST /api/social/follow
 * Body: { userId } – Target-User, dem gefolgt werden soll
 * Toggled Follow: follow wenn nicht gefolgt, unfollow wenn bereits gefolgt.
 */
export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const { userId } = (await readBody(event)) as { userId: string };

  if (!userId)
    throw createError({ statusCode: 400, message: "userId erforderlich" });
  if (userId === user.id)
    throw createError({
      statusCode: 400,
      message: "Du kannst dir selbst nicht folgen",
    });

  const existing = await getFollowRelation(user.id, userId);
  let following: boolean;

  if (existing) {
    await deleteFollow(user.id, userId);
    following = false;
  } else {
    await createFollow(user.id, userId);
    following = true;
  }

  const profile = await getProfileWithFollowers(userId);

  return {
    following,
    followersCount: profile?.followersCount ?? 0,
  };
});
