import "server-only";

import { prisma } from "@/lib/db";
import { requireSessionUser } from "@/lib/auth/session";

export async function getUserAccountIds(userId: string): Promise<string[]> {
  const accounts = await prisma.account.findMany({
    where: { userId },
    select: { id: true },
  });
  return accounts.map((account) => account.id);
}

/** 只回傳屬於該使用者的 accountId 篩選條件，杜絕看到他人或孤兒資料。 */
export function accountIdScope(
  accountIds: string[],
  activeAccountId?: string | null
): { accountId: string } | { accountId: { in: string[] } } {
  if (accountIds.length === 0) {
    return { accountId: { in: [] } };
  }
  if (activeAccountId && accountIds.includes(activeAccountId)) {
    return { accountId: activeAccountId };
  }
  return { accountId: { in: accountIds } };
}

export async function requireUserAccountScope(activeAccountId?: string | null) {
  const user = await requireSessionUser();
  const accountIds = await getUserAccountIds(user.id);
  return {
    user,
    accountIds,
    where: accountIdScope(accountIds, activeAccountId),
  };
}

export function isAccountInUserScope(
  accountIds: string[],
  resourceAccountId: string | null | undefined
): boolean {
  if (!resourceAccountId) return false;
  return accountIds.includes(resourceAccountId);
}