import type { PrismaClient } from "@prisma/client";

/** Whether the user may sign in (has at least one active access path). */
export async function canUserAuthenticate(db: PrismaClient, userId: bigint): Promise<boolean> {
  const nonTp = await db.projectUser.findFirst({
    where: { userId, projectRole: { not: "tp" } },
    select: { id: true },
  });
  if (nonTp) return true;

  const tpOwner = await db.trainingProvider.findFirst({
    where: { userId },
    select: { id: true },
  });
  if (tpOwner) return true;

  const activeStaff = await db.tpStaffMembership.findFirst({
    where: { userId, isActive: true },
    select: { id: true },
  });
  if (activeStaff) return true;

  const tpOnly = await db.projectUser.findFirst({
    where: { userId, projectRole: "tp" },
    select: { id: true },
  });
  return !tpOnly;
}

/** TP users need an active staff membership or provider ownership for this project. */
export async function hasActiveTpProjectAccess(
  db: PrismaClient,
  projectId: bigint,
  userId: bigint,
): Promise<boolean> {
  const owner = await db.trainingProvider.findFirst({
    where: { projectId, userId },
    select: { id: true },
  });
  if (owner) return true;

  const staff = await db.tpStaffMembership.findFirst({
    where: { projectId, userId, isActive: true },
    select: { id: true },
  });
  return Boolean(staff);
}
