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

// Promote a crew member to a portal login when their rank grants one (PM /
// Assistant PM / Site In-charge — Rank.grantsLogin, spec §3/§4.1). Called from
// onboarding and direct placement, inside their transaction. Creates a SITE_STAFF
// User with no password (set later via the profile / SSO). No-op when the rank
// doesn't grant a login, the crew member has no email/employee no., or a matching
// user already exists. Returns true when a login was created.

export async function maybeCreateSiteStaffLogin(
  tx: Prisma.TransactionClient,
  crew: { name: string; email: string | null; employeeId: string | null },
  rankId: string,
  siteId?: string | null
): Promise<boolean> {
  const rank = await tx.rank.findUnique({ where: { id: rankId }, select: { grantsLogin: true } });
  if (!rank?.grantsLogin) return false;
  if (!crew.email || !crew.employeeId) return false;

  const existing = await tx.user.findFirst({
    where: { OR: [{ email: crew.email }, { employeeId: crew.employeeId }] },
    select: { id: true },
  });
  if (existing) return false;

  await tx.user.create({
    data: {
      employeeId: crew.employeeId,
      email: crew.email,
      name: crew.name,
      role: "SITE_STAFF",
      passwordHash: null,
      siteId: siteId ?? null,
    },
  });
  return true;
}
