import { Prisma, Role } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { hashPassword } from '../../lib/password';
import { toPublicUser } from '../auth/auth.service';
import { ConflictError, NotFoundError } from '../../lib/errors';
import { IDENTITY_NUMBERS, type CreateSubAdminInput, type UpdateSubAdminInput } from './subadmin.schemas';
import { paginated, type Pagination } from '../../lib/pagination';
import { announceMedicalAccess, guardPasswordReset, guardRoleAssignment } from '../medical/medical-access';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { openIdNumber, sealIdNumber } from '../../lib/idNumberCrypto';

const PROFILE_SELECT = {
  photoUrl: true,
  idProofUrl: true,
  monthlySalary: true,
  salaryDay: true,
  staffCode: true,
  plantName: true,
  permanentAddress: true,
  panNumber: true,
  aadhaarNumber: true,
  uanNumber: true,
  pfNumber: true,
  esicNumber: true,
  policeVerification: true,
  medicalFitness: true,
  emergencyContactName: true,
  emergencyContactPhone: true,
  maritalStatus: true,
  uniformIssuedOn: true,
} satisfies Prisma.StaffProfileSelect;
type ProfileRow = Prisma.StaffProfileGetPayload<{ select: typeof PROFILE_SELECT }>;

const RECORD_KEYS = ['staffCode', 'plantName', 'permanentAddress', 'panNumber', 'aadhaarNumber', 'uanNumber', 'pfNumber', 'esicNumber', 'policeVerification', 'medicalFitness', 'emergencyContactName', 'emergencyContactPhone', 'maritalStatus', 'uniformIssuedOn'] as const;

const recordsOn = () => tenantHasFeature(getTenantIdOrThrow(), 'employeeRecords');

/** The employment record belongs to enterprise tenants; elsewhere its fields are ignored, as any unknown field is. */
export async function dropRecordWhereOff<T extends Partial<CreateSubAdminInput>>(input: T): Promise<T> {
  if (await recordsOn()) return input;
  const kept = { ...input };
  for (const k of RECORD_KEYS) delete kept[k];
  return kept;
}

/** Pay is not kept where the module is off (Enterprise): the fields are ignored, as any unknown field is. */
const paysHere = () => tenantHasFeature(getTenantIdOrThrow(), 'expenses');
async function dropPayWhereOff<T extends { monthlySalary?: unknown; salaryDay?: unknown }>(input: T): Promise<T> {
  if (await paysHere()) return input;
  const { monthlySalary: _salary, salaryDay: _day, ...kept } = input;
  return kept as T;
}

/**
 * The record fields actually given: undefined leaves a field alone, null clears
 * it. Government numbers go into the database sealed; only Enterprise tenants
 * hold them.
 */
function recordData(given: Partial<CreateSubAdminInput>) {
  const input: Partial<CreateSubAdminInput> = { ...given };
  for (const k of IDENTITY_NUMBERS) {
    const number = input[k];
    if (number) input[k] = sealIdNumber(number);
  }
  return Object.fromEntries(RECORD_KEYS.filter((k) => input[k] !== undefined).map((k) => [k, input[k]])) as Partial<Pick<CreateSubAdminInput, (typeof RECORD_KEYS)[number]>>;
}

const mask = (n: string | null | undefined) => (n ? `${'•'.repeat(Math.max(4, n.length - 4))}${n.slice(-4)}` : null);

/**
 * The employment record as a viewer may read it. Aadhaar is never returned in
 * full, as with an employee's ID number; the other numbers only to a hostel
 * admin, who needs them for PF and ESIC filings.
 */
function publicRecord(p: Partial<ProfileRow> | null | undefined, owner: boolean) {
  const shown = (stored: string | null | undefined) => {
    const n = openIdNumber(stored);
    return owner ? n : mask(n);
  };
  return {
    staffCode: p?.staffCode ?? null,
    plantName: p?.plantName ?? null,
    permanentAddress: p?.permanentAddress ?? null,
    panNumber: shown(p?.panNumber),
    aadhaarMasked: mask(openIdNumber(p?.aadhaarNumber)),
    uanNumber: shown(p?.uanNumber),
    pfNumber: shown(p?.pfNumber),
    esicNumber: shown(p?.esicNumber),
    policeVerification: p?.policeVerification ?? null,
    medicalFitness: p?.medicalFitness ?? null,
    emergencyContactName: p?.emergencyContactName ?? null,
    emergencyContactPhone: p?.emergencyContactPhone ?? null,
    maritalStatus: p?.maritalStatus ?? null,
    uniformIssuedOn: p?.uniformIssuedOn ? p.uniformIssuedOn.toISOString().slice(0, 10) : null,
  };
}

/** A staff ID is one person's within a hostel. */
async function checkStaffCode(staffCode: unknown, userId?: string) {
  if (typeof staffCode !== 'string' || !staffCode) return;
  const clash = await db.staffProfile.findFirst({ where: { staffCode, ...(userId ? { userId: { not: userId } } : {}) }, select: { id: true } });
  if (clash) throw new ConflictError('Someone else already has that staff ID');
}

/**
 * Hostel Admin operation — tenant-bound, so it uses the SCOPED `db` client:
 * `tenantId` is injected automatically from the request context. The admin
 * literally cannot create a user in another tenant.
 */
export async function createSubAdmin(given: CreateSubAdminInput, createdById: string) {
  const input = await dropPayWhereOff(given);
  await checkStaffCode(input.staffCode);
  const user = await db.user.create({
    data: {
      role: input.role,
      name: input.name,
      email: input.email,
      phone: input.phone,
      passwordHash: await hashPassword(input.password),
      createdById,
      // tenantId is injected by the scoping layer — do NOT set it here.
    },
  });
  // Sprint 6: salary lives on the staff profile, created only when given. So does the employment record.
  const record = recordData(input);
  if (input.monthlySalary != null || input.salaryDay != null || Object.values(record).some((v) => v !== null)) {
    await db.staffProfile.create({ data: { userId: user.id, tenantId: user.tenantId!, monthlySalary: input.monthlySalary ?? null, salaryDay: input.salaryDay ?? null, ...record } });
  }
  return toPublicUser(user);
}

/** Counts for the staff stat cards, via COUNT rather than loaded rows. */
export async function subAdminStats() {
  const staffRoles = { in: [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] };
  const [total, wardens, mess, custom] = await Promise.all([
    db.user.count({ where: { role: staffRoles } }),
    db.user.count({ where: { role: Role.WARDEN } }),
    db.user.count({ where: { role: Role.MESS_ADMIN } }),
    db.user.count({ where: { role: staffRoles, customRoleId: { not: null } } }),
  ]);
  return { total, wardens, mess, custom, onDefaults: total - custom };
}

export async function listSubAdmins(
  pagination?: Pagination | null,
  filters: { q?: string; role?: Role } = {},
  owner = false,
) {
  const where = {
    role: filters.role ? filters.role : { in: [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] },
    ...(filters.q
      ? {
          OR: [
            { name: { contains: filters.q, mode: 'insensitive' as const } },
            { email: { contains: filters.q, mode: 'insensitive' as const } },
          ],
        }
      : {}),
  };
  const include = {
    customRole: { select: { id: true, name: true } },
    staffProfile: { select: PROFILE_SELECT },
  };
  const orderBy = { createdAt: 'desc' as const };
  const withRecord = await recordsOn();
  const withPay = await paysHere();
  const toStaff = (u: Awaited<ReturnType<typeof db.user.findMany>>[number] & {
    customRole?: { id: string; name: string } | null;
    staffProfile?: ProfileRow | null;
  }) => ({
    ...toPublicUser(u),
    customRole: u.customRole ?? null,
    // Flattened onto the row: a staff member has at most one profile, and the
    // clients only ever want the two keys.
    photoUrl: u.staffProfile?.photoUrl ?? null,
    idProofUrl: u.staffProfile?.idProofUrl ?? null,
    monthlySalary: withPay ? u.staffProfile?.monthlySalary ?? null : null,
    salaryDay: withPay ? u.staffProfile?.salaryDay ?? null : null,
    ...(withRecord ? { record: publicRecord(u.staffProfile, owner) } : {}),
  });

  if (!pagination) {
    const users = await db.user.findMany({ where, include, orderBy });
    return users.map(toStaff);
  }

  const [users, total] = await Promise.all([
    db.user.findMany({ where, include, orderBy, skip: pagination.skip, take: pagination.limit }),
    db.user.count({ where }),
  ]);
  return paginated(users.map(toStaff), total, pagination);
}

/** Assign (or clear, with null) a custom role for a staff user. */
export async function assignRole(userId: string, customRoleId: string | null, actorId: string, owner = false) {
  const user = await db.user.findFirst({ where: { id: userId, role: { in: [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] } } });
  if (!user) throw new NotFoundError('Staff member not found');
  if (customRoleId) {
    const role = await db.customRole.findFirst({ where: { id: customRoleId } });
    if (!role) throw new NotFoundError('Custom role not found');
  }
  const gainsMedical = await guardRoleAssignment(actorId, userId, customRoleId);
  await db.user.update({
    where: { id: userId },
    data: { customRoleId },
    include: {
      customRole: { select: { id: true, name: true } },
      staffProfile: { select: { photoUrl: true, idProofUrl: true } },
    },
  });
  if (gainsMedical) announceMedicalAccess(actorId, [userId]);
  // Re-read rather than trusting the update's own include: a nested upsert
  // does not refresh the relation in the same query, so the response came back
  // with the photo the row had before the write.
  return getSubAdmin(userId, owner);
}

/**
 * Every staff mutation goes through this lookup, so the same two guarantees
 * hold everywhere: the scoped client keeps it inside the caller's tenant, and
 * the role filter keeps it to WARDEN/MESS_ADMIN — a hostel admin can never
 * edit, reset or delete another admin, a student, or themselves through here.
 */
async function findStaffOrThrow(userId: string) {
  const user = await db.user.findFirst({
    where: { id: userId, role: { in: [Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] } },
  });
  if (!user) throw new NotFoundError('Staff member not found');
  return user;
}

export async function getSubAdmin(userId: string, owner = false) {
  await findStaffOrThrow(userId);
  const user = await db.user.findFirst({
    where: { id: userId },
    include: {
      customRole: { select: { id: true, name: true, permissions: true } },
      staffProfile: { select: PROFILE_SELECT },
    },
  });
  const withPay = await paysHere();
  return {
    ...toPublicUser(user!),
    customRole: user!.customRole,
    photoUrl: user!.staffProfile?.photoUrl ?? null,
    idProofUrl: user!.staffProfile?.idProofUrl ?? null,
    monthlySalary: withPay ? user!.staffProfile?.monthlySalary ?? null : null,
    salaryDay: withPay ? user!.staffProfile?.salaryDay ?? null : null,
    ...((await recordsOn()) ? { record: publicRecord(user!.staffProfile, owner) } : {}),
  };
}

export async function updateSubAdmin(userId: string, given: UpdateSubAdminInput, owner = false) {
  const input = await dropPayWhereOff(given);
  const existing = await findStaffOrThrow(userId);
  await checkStaffCode(input.staffCode, userId);
  const record = recordData(input);

  if (input.email && input.email !== existing.email) {
    // Email is unique platform-wide, so check unscoped — a clash with another
    // tenant's user is still a clash, and a bare Prisma P2002 would be opaque.
    const taken = await prismaUnscoped.user.findUnique({ where: { email: input.email } });
    if (taken) throw new ConflictError('That email is already registered');
  }

  await db.user.update({
    where: { id: userId },
    data: {
      ...(input.role !== undefined ? { role: input.role } : {}),
      ...(input.name !== undefined ? { name: input.name } : {}),
      ...(input.email !== undefined ? { email: input.email } : {}),
      // Blank clears the number; omitting the field leaves it alone.
      ...(input.phone !== undefined ? { phone: input.phone || null } : {}),
      // The profile row is created on first use rather than at onboarding, so
      // staff who never upload anything carry no empty record.
      ...(input.photoUrl !== undefined || input.idProofUrl !== undefined || input.monthlySalary !== undefined || input.salaryDay !== undefined || Object.keys(record).length > 0
        ? {
            staffProfile: {
              upsert: {
                create: {
                  tenantId: existing.tenantId!,
                  ...(input.photoUrl !== undefined ? { photoUrl: input.photoUrl } : {}),
                  ...(input.idProofUrl !== undefined ? { idProofUrl: input.idProofUrl } : {}),
                  ...(input.monthlySalary !== undefined ? { monthlySalary: input.monthlySalary } : {}),
                  ...(input.salaryDay !== undefined ? { salaryDay: input.salaryDay } : {}),
                  ...record,
                },
                update: {
                  ...(input.photoUrl !== undefined ? { photoUrl: input.photoUrl } : {}),
                  ...(input.idProofUrl !== undefined ? { idProofUrl: input.idProofUrl } : {}),
                  ...(input.monthlySalary !== undefined ? { monthlySalary: input.monthlySalary } : {}),
                  ...(input.salaryDay !== undefined ? { salaryDay: input.salaryDay } : {}),
                  ...record,
                },
              },
            },
          }
        : {}),
    },
    include: { customRole: { select: { id: true, name: true } } },
  });
  // Re-read rather than trusting this update's include: a nested upsert
  // does not refresh the relation in the same query, so the photo came
  // back as it was before the write.
  return getSubAdmin(userId, owner);
}

/**
 * Admin-set password for a staff member who is locked out.
 *
 * There is no self-service reset, so this is the recovery path. Stamping
 * passwordChangedAt cuts off any session that member still has open — if the
 * reason for the reset is a compromised account, leaving those alive would
 * defeat the point.
 */
export async function resetSubAdminPassword(userId: string, newPassword: string) {
  await findStaffOrThrow(userId);
  await guardPasswordReset(userId);
  await db.user.update({
    where: { id: userId },
    data: { passwordHash: await hashPassword(newPassword), passwordChangedAt: new Date() },
  });
}

/**
 * Remove a staff account.
 *
 * The rows they touched (notices, payments, expenses) record the author as a
 * plain id/name rather than a foreign key, so history survives the deletion
 * instead of cascading away with them.
 */
export async function deleteSubAdmin(userId: string) {
  const user = await findStaffOrThrow(userId);
  await db.user.delete({ where: { id: userId } });
  return { id: userId, name: user.name };
}

/**
 * A staff member replacing their own photo.
 *
 * Scoped by the signed-in user rather than an id from the client, so it can
 * only ever reach their own record. Their documents are not editable here —
 * only a hostel admin changes those.
 */
export async function updateMyStaffPhoto(userId: string, photoUrl: string | null) {
  const user = await db.user.findFirst({ where: { id: userId } });
  if (!user) throw new NotFoundError('Staff member not found');

  await db.staffProfile.upsert({
    where: { userId },
    create: { userId, tenantId: user.tenantId!, photoUrl },
    update: { photoUrl },
  });

  // Re-read rather than returning the key that was passed in: every other
  // route in this module answers with the full staff record, and a caller
  // that has just changed its avatar is the one most likely to re-render it.
  //
  // Not through getSubAdmin: that guards on "staff" meaning WARDEN or
  // MESS_ADMIN, so a hostel admin changing their own photo saved it and then
  // got "Staff member not found" reading it back. This route is scoped to
  // the session and already authorises all three roles.
  const saved = await db.user.findFirst({
    where: { id: userId },
    include: {
      customRole: { select: { id: true, name: true, permissions: true } },
      staffProfile: { select: { photoUrl: true, idProofUrl: true } },
    },
  });
  return {
    ...toPublicUser(saved!),
    customRole: saved!.customRole,
    photoUrl: saved!.staffProfile?.photoUrl ?? null,
    idProofUrl: saved!.staffProfile?.idProofUrl ?? null,
  };
}
