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

export async function getFollowRelation(
  followerId: string,
  followingId: string,
) {
  const db = usePrisma();
  return db.userFollow.findUnique({
    where: { followerId_followingId: { followerId, followingId } },
  });
}

export async function createFollow(followerId: string, followingId: string) {
  const db = usePrisma();
  const exists = await db.userFollow.findUnique({
    where: { followerId_followingId: { followerId, followingId } },
  });
  if (exists) return;
  await db.userFollow.create({ data: { followerId, followingId } });
  await db.profile.update({
    where: { id: followingId },
    data: { followersCount: { increment: 1 } },
  });
}

export async function deleteFollow(followerId: string, followingId: string) {
  const db = usePrisma();
  const exists = await db.userFollow.findUnique({
    where: { followerId_followingId: { followerId, followingId } },
  });
  if (!exists) return;
  await db.userFollow.delete({
    where: { followerId_followingId: { followerId, followingId } },
  });
  // Nie unter 0
  const profile = await db.profile.findUnique({
    where: { id: followingId },
    select: { followersCount: true },
  });
  if (profile && profile.followersCount > 0) {
    await db.profile.update({
      where: { id: followingId },
      data: { followersCount: { decrement: 1 } },
    });
  }
}

/** Gibt ein Set der userIds zurück, denen followerId bereits folgt (Batch-Variante). */
export async function getFollowingSet(
  followerId: string,
  followingIds: string[],
): Promise<Set<string>> {
  if (followingIds.length === 0) return new Set();
  const db = usePrisma();
  const rows = await db.userFollow.findMany({
    where: { followerId, followingId: { in: followingIds } },
    select: { followingId: true },
  });
  return new Set(rows.map((r) => r.followingId));
}

export async function getProfileWithFollowers(userId: string) {
  const db = usePrisma();
  return db.profile.findUnique({
    where: { id: userId },
    select: {
      followersCount: true,
      username: true,
      avatar: true,
      nickname: true,
    },
  });
}
