import { Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ForbiddenError } from '../../lib/errors';
import { effectivePermissions } from '../../lib/permissions';
import { inBackground, pushTo } from '../notifications/notifications.service';

/**
 * Who may open medical records is decided by roles the owner controls, so
 * that power is watched (Sprint 7 hardening, TEPL): nobody can give it to
 * themselves, the owner cannot take over a medical login by resetting its
 * password, and whenever a login gains it the OHC staff already holding it
 * (and the owner) are told. The owner's medical page lists who holds it now.
 */

const MEDICAL = 'MANAGE_MEDICAL';
const holds = (perms: string[] | null | undefined) => !!perms?.includes(MEDICAL);

/** Staff logins that can open records now (the owner never can). */
export async function ohcLogins() {
  const staff = await db.user.findMany({ where: { role: { in: [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] }, customRole: { permissions: { has: MEDICAL } } }, select: { id: true, name: true, email: true, customRole: { select: { name: true } } }, orderBy: { name: 'asc' } });
  return staff.map((u) => ({ id: u.id, name: u.name, email: u.email, role: u.customRole?.name ?? null }));
}

export async function isMedicalLogin(userId: string) {
  const u = await db.user.findFirst({ where: { id: userId }, select: { role: true, customRole: { select: { permissions: true } } } });
  return !!u && u.role !== Role.HOSTEL_ADMIN && effectivePermissions(u.role, u.customRole?.permissions).includes(MEDICAL);
}

/** Before a role is given to a login: never medical access to yourself. */
export async function guardRoleAssignment(actorId: string, userId: string, customRoleId: string | null) {
  if (!customRoleId) return false;
  const role = await db.customRole.findFirst({ where: { id: customRoleId }, select: { permissions: true } });
  const before = await db.user.findFirst({ where: { id: userId }, select: { customRole: { select: { permissions: true } } } });
  const gains = holds(role?.permissions) && !holds(before?.customRole?.permissions);
  if (gains && actorId === userId) throw new ForbiddenError('You cannot give yourself access to medical records');
  return gains;
}

/** Before a role's permissions change: never add medical access to a role you hold. */
export async function guardRoleEdit(actorId: string, roleId: string, nextPermissions: string[] | undefined) {
  if (!nextPermissions) return [];
  const role = await db.customRole.findFirst({ where: { id: roleId }, select: { permissions: true } });
  if (!role || holds(role.permissions) || !holds(nextPermissions)) return [];
  const members = await db.user.findMany({ where: { customRoleId: roleId }, select: { id: true } });
  if (members.some((m) => m.id === actorId)) throw new ForbiddenError('You cannot give your own role access to medical records');
  return members.map((m) => m.id);
}

/** A medical login keeps its own password: it resets it from the sign-in page, not through the owner. */
export async function guardPasswordReset(userId: string) {
  if (await isMedicalLogin(userId)) throw new ForbiddenError('A medical records (OHC) login resets its own password from the sign-in page');
}

/** Tells the OHC staff already holding access, and the owner, that more logins now can open records. */
export function announceMedicalAccess(actorId: string, userIds: string[]) {
  if (!userIds.length) return;
  const tenantId = getTenantIdOrThrow();
  inBackground('push: medical access granted', async () => {
    const [who, actor, current, owners] = await Promise.all([
      db.user.findMany({ where: { id: { in: userIds } }, select: { name: true } }),
      db.user.findFirst({ where: { id: actorId }, select: { name: true } }),
      ohcLogins(),
      db.user.findMany({ where: { role: Role.HOSTEL_ADMIN }, select: { id: true } }),
    ]);
    const to = [...new Set([...current.map((c) => c.id).filter((id) => !userIds.includes(id)), ...owners.map((o) => o.id)])];
    await pushTo(tenantId, 'MEDICAL_ACCESS', userIds[0], to, { title: 'Medical records: new access', body: `${who.map((w) => w.name).join(', ')} can now open medical records (given by ${actor?.name ?? 'someone'}).`, data: {} });
  });
}
