import { BedStatus, PricingMode, Role, StayStatus, TenantKind } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantContext, getTenantIdOrThrow } from '../../lib/tenantContext';
import { hashPassword } from '../../lib/password';
import { NO_LOGIN_EMAIL_DOMAIN, placeholderEmail } from '../../lib/no-login';
import { randomBytes } from 'node:crypto';
import { toPublicUser } from '../auth/auth.service';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import type { OnboardStudentInput, UpdateStudentInput } from './students.schemas';
import { paginated, type Pagination } from '../../lib/pagination';
import { Prisma } from '@prisma/client';
import { applyMoveOutCredit } from '../billing/billing-rules.service';
import { duplicateIdentityField, phoneKey } from '../../lib/person-identity';
import { employeeData } from './employee-record';
import { tenantHasFeature, tenantKindOf } from '../../middleware/requireFeature';
import { openIdNumber, sealIdNumber } from '../../lib/idNumberCrypto';

function currentTenantId(): string {
  const ctx = getTenantContext();
  if (!ctx?.tenantId) throw new BadRequestError('Missing tenant context');
  return ctx.tenantId;
}

/** Date-only strings from the client become UTC-midnight Dates; the
 *  verified-at stamps follow the status. */
function complianceData(input: Record<string, unknown>) {
  const out: Record<string, unknown> = {};
  const toDate = (v: unknown) => (typeof v === 'string' ? new Date(`${v}T00:00:00.000Z`) : v === null ? null : undefined);
  for (const k of ['address', 'city', 'state', 'postalCode', 'depositAmount', 'depositPaid', 'depositMethod', 'depositReference', 'depositRefunded', 'depositNote', 'kycIdType', 'kycIdNumber', 'kycAddressProofUrl', 'kycStatus', 'policeVerificationStatus', 'policeVerificationRef', 'policeVerificationDocUrl']) {
    if (k in input) out[k] = input[k];
  }
  for (const k of ['depositPaidAt', 'depositRefundedAt', 'policeVerificationDate']) {
    if (k in input) out[k] = toDate(input[k]);
  }
  if (input.kycStatus === 'VERIFIED') out.kycVerifiedAt = new Date();
  if (input.kycStatus === 'PENDING') out.kycVerifiedAt = null;
  return out;
}

/** Aadhaar-style masking: only the last four survive. */
function maskId(n: string | null | undefined): string | null {
  if (!n) return null;
  return n.length <= 4 ? '••••' : `${'•'.repeat(Math.max(4, n.length - 4))}${n.slice(-4)}`;
}

/** The profile with the ID number masked. Never returned raw. */
function publicProfile<
  T extends {
    kycIdNumber?: string | null;
    stays?: Array<{
      id: string;
      status: StayStatus;
      plannedCheckIn: Date;
      plannedCheckOut: Date;
      bed: { id: string; label: string; status: BedStatus; room: { id: string; number: string; floor: number | null } };
    }>;
  },
>(p: T) {
  const { kycIdNumber, stays, ...rest } = p;
  return {
    ...rest,
    ...(stays ? { activeStay: stays[0] ?? null } : {}),
    kycIdNumberMasked: maskId(openIdNumber(kycIdNumber)),
    hasKycIdNumber: !!kycIdNumber,
  };
}

/** An Enterprise tenant's ID number goes in sealed; other kinds store theirs as they always have. */
async function sealKyc(data: Record<string, unknown>) {
  if (typeof data.kycIdNumber !== 'string' || !data.kycIdNumber) return data;
  const tenantId = currentTenantId();
  if ((await tenantKindOf(tenantId)) !== TenantKind.ENTERPRISE) return data;
  return { ...data, kycIdNumber: sealIdNumber(data.kycIdNumber, tenantId) };
}

const assignedAccommodationWhere = (now = new Date()): Prisma.StudentProfileWhereInput => ({
  OR: [
    { bed: { is: { room: { floor: { not: null } } } } },
    {
      stays: {
        some: {
          OR: [{ status: StayStatus.CHECKED_IN }, { status: StayStatus.BOOKED, plannedCheckOut: { gt: now } }],
          bed: { room: { floor: { not: null } } },
        },
      },
    },
  ],
});

const studentInclude = (now = new Date()) => Prisma.validator<Prisma.StudentProfileInclude>()({
  user: { select: { id: true, name: true, email: true, phone: true, role: true, hasLogin: true } },
  bed: { include: { room: { select: { id: true, number: true, floor: true } } } },
  // Sprint 1 (TEPL): the employee record. Null for everyone else.
  department: { select: { id: true, name: true } },
  defaultShift: { select: { id: true, code: true, name: true } },
  arrivalBed: { select: { id: true, label: true, room: { select: { id: true, number: true } } } },
  // A dormitory booking reserves accommodation before check-in, while bedId
  // correctly stays null until the customer physically arrives.
  stays: {
    where: {
      OR: [{ status: StayStatus.CHECKED_IN }, { status: StayStatus.BOOKED, plannedCheckOut: { gt: now } }],
      bed: { room: { floor: { not: null } } },
    },
    orderBy: { plannedCheckIn: 'asc' as const },
    take: 1,
    select: {
      id: true,
      status: true,
      plannedCheckIn: true,
      plannedCheckOut: true,
      bed: { select: { id: true, label: true, status: true, room: { select: { id: true, number: true, floor: true } } } },
    },
  },
});

/**
 * Onboard a student end-to-end: create the STUDENT user + profile, optionally
 * assigning a bed — atomically. tenantId is passed explicitly so the writes are
 * correct whether or not the extension applies inside the interactive tx.
 */
export async function onboardStudent(input: OnboardStudentInput, createdById: string, propertyId?: string) {
  // Plans no longer cap people, only properties and beds: a customer without
  // a bed costs the hostel nothing, and a bed is checked when it is created.
  const tenantId = currentTenantId();
  await assertNoDuplicateStudent(input);
  const employee = await employeeData(input);
  // No email means no login: a placeholder address and a password nobody
  // holds. The schema guarantees email and password arrive together.
  const hasLogin = input.email !== undefined && input.password !== undefined;
  const passwordHash = await hashPassword(hasLogin ? input.password! : randomBytes(24).toString('base64url'));

  return db.$transaction(async (tx) => {
    const user = await tx.user.create({
      data: {
        tenantId,
        role: Role.STUDENT,
        name: input.name,
        email: hasLogin ? input.email! : placeholderEmail(),
        phone: input.phone,
        passwordHash,
        hasLogin,
        createdById,
      },
    });

    let bedId: string | undefined;
    // A bed decides the property; otherwise use the active property.
    let resolvedPropertyId = propertyId;
    if (input.bedId) {
      const bed = await tx.bed.findFirst({ where: { id: input.bedId, archivedAt: null }, include: { room: { select: { propertyId: true, floor: true } } } });
      if (!bed || bed.tenantId !== tenantId) throw new NotFoundError('Bed not found');
      if (bed.room.floor == null) throw new ConflictError('Set a floor for this room before assigning its beds');
      if (bed.status !== BedStatus.VACANT) throw new ConflictError('Bed is not vacant');
      await tx.bed.update({ where: { id: bed.id }, data: { status: BedStatus.OCCUPIED } });
      bedId = bed.id;
      resolvedPropertyId = bed.room.propertyId;
    }

    // A student with no property would be invisible in every property-scoped
    // list, and so impossible to reach and assign a bed to. If neither the bed
    // nor the request context named one, fall back to the tenant's first
    // property rather than leaving the row orphaned.
    if (!resolvedPropertyId) {
      const fallback = await tx.property.findFirst({ orderBy: { createdAt: 'asc' }, select: { id: true } });
      resolvedPropertyId = fallback?.id;
    }

    const profile = await tx.studentProfile.create({
      data: {
        tenantId,
        userId: user.id,
        guardianName: input.guardianName,
        guardianPhone: input.guardianPhone,
        parentName: input.parentName,
        parentPhone: input.parentPhone,
        idProofUrl: input.idProofUrl,
        photoUrl: input.photoUrl,
        ...(await sealKyc(complianceData(input as Record<string, unknown>))),
        ...employee,
        bedId,
        propertyId: resolvedPropertyId,
        // Keep an explicitly recorded move-in date even when accommodation is
        // booked later; otherwise taking a bed starts residency today.
        ...(input.movedInAt ? { movedInAt: input.movedInAt } : bedId ? { movedInAt: new Date() } : {}),
      },
      include: studentInclude(),
    });
    if (bedId) {
      const bedRoom = await tx.bed.findFirst({ where: { id: bedId }, select: { roomId: true } });
      if (bedRoom) await reconcileRoomBilling(tx, profile.id, bedRoom.roomId);
    }
    return { user: toPublicUser(user), profile: publicProfile(profile) };
  });
}

/**
 * Manual onboarding and Excel import use the same duplicate rule. Email is
 * globally unique for logins; phone and identity number are checked within
 * the current tenant after normalising common formatting differences.
 */
export async function assertNoDuplicateStudent(input: Pick<OnboardStudentInput, 'email' | 'phone' | 'kycIdNumber'>) {
  const email = input.email?.trim();
  if (email) {
    // Email uniqueness is case-insensitive from a person's perspective even
    // when the database collation is not. This also keeps manual onboarding
    // and Excel import on the same duplicate rule.
    const owner = await prismaUnscoped.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: { tenantId: true, role: true } });
    if (owner) {
      const sameTenantCustomer = owner.tenantId === currentTenantId() && owner.role === Role.STUDENT;
      throw new ConflictError(sameTenantCustomer ? 'A customer with this email already exists.' : 'That email is already registered.');
    }
  }
  const normalizedPhone = phoneKey(input.phone);
  const lastFour = normalizedPhone?.slice(-4);
  const candidates = await db.studentProfile.findMany({
    where: {
      OR: [
        ...(email ? [{ user: { email: { equals: email, mode: 'insensitive' as const } } }] : []),
        ...(lastFour ? [{ user: { phone: { contains: lastFour } } }] : []),
        ...(input.kycIdNumber ? [{ kycIdNumber: { not: null } }] : []),
      ],
    },
    select: { kycIdNumber: true, user: { select: { email: true, phone: true } } },
  });
  for (const candidate of candidates) {
    const field = duplicateIdentityField(input, { ...candidate.user, kycIdNumber: openIdNumber(candidate.kycIdNumber) });
    if (field) throw new ConflictError(`A customer with this ${field} already exists.`);
  }
}



/**
 * Remove a student entirely.
 *
 * Refused once they have been invoiced: an invoice without the student it was
 * raised against is a hole in the books, and the accounts must stay whole.
 * "Move out" is the answer for someone who has left — it frees their bed and
 * keeps the history.
 */
export async function deleteStudent(id: string) {
  const profile = await db.studentProfile.findFirst({
    where: { id },
    include: { tenant: { select: { kind: true } }, _count: { select: { invoices: true } } },
  });
  if (!profile) throw new NotFoundError('Student not found');
  if (profile._count.invoices > 0) {
    const resident = profile.tenant.kind === TenantKind.DORMITORY ? 'customer' : 'resident';
    throw new ConflictError(
      `This ${resident} has invoices, so their record cannot be deleted. Move them out instead — their bed is freed and the history is kept.`,
      'STUDENT_HAS_INVOICES',
    );
  }

  await db.$transaction(async (tx) => {
    if (profile.bedId) {
      await tx.bed.update({ where: { id: profile.bedId }, data: { status: BedStatus.VACANT } });
    }
    // A room cannot keep pointing at a student who no longer exists.
    await tx.room.updateMany({ where: { billedStudentProfileId: id }, data: { billedStudentProfileId: null } });
    await tx.messAttendance.deleteMany({ where: { studentProfileId: id } });
    const requestIds = (await tx.studentRequest.findMany({ where: { studentProfileId: id }, select: { id: true } })).map((r) => r.id);
    if (requestIds.length) await tx.attachment.deleteMany({ where: { ownerType: 'REQUEST', ownerId: { in: requestIds } } });
    await tx.studentRequestReply.deleteMany({ where: { request: { studentProfileId: id } } });
    await tx.studentRequest.deleteMany({ where: { studentProfileId: id } });
    await tx.messComplaintReply.deleteMany({ where: { complaint: { studentProfileId: id } } });
    await tx.messComplaint.deleteMany({ where: { studentProfileId: id } });
    await tx.messSubscription.deleteMany({ where: { studentProfileId: id } });
    await tx.biometricPunch.deleteMany({ where: { studentProfileId: id } });
    await tx.studentProfile.delete({ where: { id } });
    await tx.user.delete({ where: { id: profile.userId } });
  });
}

/**
 * Counts for the list's stat cards.
 *
 * Separate from the list because the cards describe the whole property while
 * the list holds one page — deriving them from the rows on screen would show
 * "25 students" for any hostel with more than a page of them. Computed with
 * COUNT so no rows are loaded to produce a number.
 */
export async function studentStats(propertyId?: string) {
  const base = propertyId ? { propertyId } : {};
  const monthStart = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1));
  const [total, assigned, kycPending, pvPending, depositDue, joinedThisMonth] = await Promise.all([
    db.studentProfile.count({ where: base }),
    db.studentProfile.count({
      where: {
        ...base,
        ...assignedAccommodationWhere(),
      },
    }),
    db.studentProfile.count({ where: { ...base, kycStatus: { not: 'VERIFIED' } } }),
    db.studentProfile.count({
      where: { ...base, policeVerificationStatus: { in: ['PENDING', 'SUBMITTED'] } },
    }),
    // depositAmount > depositPaid compares two columns, which `count` cannot
    // express, so it is counted in SQL (Sprint L4) rather than by loading every
    // resident with a deposit.
    depositDueCount(propertyId),
    db.studentProfile.count({ where: { ...base, createdAt: { gte: monthStart } } }),
  ]);
  return {
    total,
    assigned,
    unassigned: total - assigned,
    kycPending,
    pvPending,
    depositDue,
    joinedThisMonth,
  };
}

/** Residents whose agreed deposit is more than they have paid of it, in this tenant (and property). */
export async function depositDueCount(propertyId?: string) {
  const tenantId = getTenantIdOrThrow();
  const [row] = await prismaUnscoped.$queryRaw<{ n: bigint }[]>(Prisma.sql`
    SELECT count(*) AS n FROM "StudentProfile"
    WHERE "tenantId" = ${tenantId} ${propertyId ? Prisma.sql`AND "propertyId" = ${propertyId}` : Prisma.empty}
      AND "depositAmount" IS NOT NULL AND "depositAmount" > "depositPaid"`);
  return Number(row?.n ?? 0);
}

export interface StudentListFilters {
  /** Matches the student's name or email, case-insensitively. */
  q?: string;
  /** True: a live bed or open booking. False: neither. */
  assigned?: boolean;
  /** Sprint 1 (TEPL): one department. */
  departmentId?: string;
}

export async function listStudents(
  propertyId?: string,
  pagination?: Pagination | null,
  filters: StudentListFilters = {},
) {
  // Search and the assigned filter run in SQL, not in the client: a paginated
  // client only holds one page, so filtering there would search the page
  // rather than the table.
  // Enterprise tenants also find people by employee ID, card number or
  // terminal id — what the front desk has in hand.
  const byEmployee = !!filters.q && (await tenantHasFeature(currentTenantId(), 'employeeRecords'));
  const userMatch: Prisma.UserWhereInput = {
    OR: [
      { name: { contains: filters.q, mode: 'insensitive' } },
      { phone: { contains: filters.q } },
      // A placeholder address is not something anyone would type to find a person.
      { AND: [{ email: { contains: filters.q, mode: 'insensitive' } }, { email: { not: { endsWith: `@${NO_LOGIN_EMAIL_DOMAIN}` } } }] },
    ],
  };
  const where: Prisma.StudentProfileWhereInput = {
    ...(propertyId ? { propertyId } : {}),
    ...(filters.departmentId ? { departmentId: filters.departmentId } : {}),
    ...(filters.assigned === undefined
      ? {}
      : filters.assigned
        ? assignedAccommodationWhere()
        : { NOT: assignedAccommodationWhere() }),
    ...(filters.q
      ? byEmployee
        ? {
            OR: [
              { user: userMatch },
              { employeeCode: { contains: filters.q, mode: 'insensitive' } },
              { cardNumber: { contains: filters.q, mode: 'insensitive' } },
              { biometricId: filters.q },
            ],
          }
        : { user: userMatch }
      : {}),
  };
  const orderBy = { createdAt: 'desc' } as const;

  // No page asked for: answer exactly as before, so existing clients are
  // unaffected.
  // Both branches mask the KYC ID number: a roster must never be an
  // ID-number dump (the paging refactor had dropped this).
  if (!pagination) {
    const rows = await db.studentProfile.findMany({ where, include: studentInclude(), orderBy });
    return rows.map(publicProfile);
  }

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

/** (Re)assign a student to a bed, freeing any previous bed. */

/**
 * Keep ROOM-priced rooms pointing at someone who actually lives there.
 *
 * Called whenever a student lands on a bed. Two jobs:
 *   1. If they were the billed student of a DIFFERENT room, clear that link —
 *      otherwise the room they left keeps invoicing them indefinitely.
 *   2. If the room they moved into prices by ROOM and nobody is billed for it
 *      yet, make them the responsible student. The first occupant is the
 *      sensible default, and an admin can reassign it from the room.
 *
 * Leaving a room with occupants and no billed student is allowed (it happens
 * naturally when the responsible student moves out) but generates no rent, so
 * the dashboard surfaces it rather than letting it pass silently.
 */
// The scoped client is $extends-wrapped, so its transaction client is not
// Prisma.TransactionClient — derive the type from the client itself.
type Tx = Parameters<Parameters<typeof db.$transaction>[0]>[0];

async function reconcileRoomBilling(tx: Tx, profileId: string, newRoomId: string | null) {
  const previous = await tx.room.findFirst({ where: { billedStudentProfileId: profileId } });
  if (previous && previous.id !== newRoomId) {
    await tx.room.update({ where: { id: previous.id }, data: { billedStudentProfileId: null } });
  }
  // Moving out entirely: there is no new room to nominate them for.
  if (newRoomId === null) return;

  const room = await tx.room.findFirst({
    where: { id: newRoomId },
    include: { property: { select: { pricingMode: true } } },
  });
  if (
    room &&
    room.property.pricingMode === PricingMode.ROOM &&
    !room.billedStudentProfileId
  ) {
    await tx.room.update({ where: { id: room.id }, data: { billedStudentProfileId: profileId } });
  }
}

/**
 * Move a student out of their bed without deleting them.
 *
 * The bed goes back to VACANT and, if they were the one billed for a
 * ROOM-priced room, that link is cleared — a room cannot keep invoicing
 * someone who no longer lives there. The student stays in the property so
 * their invoice history and documents survive the move.
 */
export async function vacateBed(profileId: string, vacatedAt: Date = new Date()) {
  const tenantId = currentTenantId();
  return db.$transaction(async (tx) => {
    const profile = await tx.studentProfile.findFirst({ where: { id: profileId } });
    if (!profile || profile.tenantId !== tenantId) throw new NotFoundError('Student not found');
    if (profile.bedId) {
      await tx.bed.update({ where: { id: profile.bedId }, data: { status: BedStatus.VACANT } });
    }
    await reconcileRoomBilling(tx, profileId, null);
    // Under pro-rata, the unused days of the current cycle come off the open invoice.
    if (profile.bedId) await applyMoveOutCredit(tx, profileId, vacatedAt);
    return tx.studentProfile.update({ where: { id: profileId }, data: { bedId: null, vacatedAt }, include: studentInclude() });
  });
}

/**
 * One student in full, for the profile screen.
 *
 * Property-scoped as well as tenant-scoped: a warden with one property must
 * not read a student filed under another, and answering "not found" rather
 * than "forbidden" keeps the other property's roster unguessable.
 */
/**
 * The scoping check, shared by every route that addresses a student by id.
 *
 * Returns the raw row: callers that mutate need `userId` and the current
 * values, not the masked public shape.
 */
async function findStudentOrThrow(profileId: string, propertyId?: string) {
  const tenantId = currentTenantId();
  const profile = await db.studentProfile.findFirst({
    where: { id: profileId },
    // Wider than the list's `studentInclude`: the detail page names the
    // property and the room type, which a row in the list never shows.
    include: {
      user: {
        select: { id: true, name: true, email: true, phone: true, role: true, hasLogin: true, createdAt: true },
      },
      bed: { include: { room: { select: { id: true, number: true, floor: true, type: true } } } },
      property: { select: { id: true, name: true, city: true } },
      // Sprint 1 (TEPL): the employee record. Null for everyone else.
      department: { select: { id: true, name: true } },
      defaultShift: { select: { id: true, code: true, name: true } },
      arrivalBed: { select: { id: true, label: true, room: { select: { id: true, number: true } } } },
    },
  });
  if (!profile || profile.tenantId !== tenantId) throw new NotFoundError('Student not found');
  if (propertyId && profile.propertyId !== propertyId) throw new NotFoundError('Student not found');
  return profile;
}

export async function getStudent(profileId: string, propertyId?: string) {
  const profile = await findStudentOrThrow(profileId, propertyId);

  // Their money, summarised — the question anyone opening a student asks.
  const invoices = await db.invoice.findMany({
    where: { studentProfileId: profileId },
    orderBy: { periodMonth: 'desc' },
    take: 12,
    include: { payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
  });
  const billed = invoices.reduce((n, i) => n + i.amount, 0);
  const paid = invoices.reduce((n, i) => n + i.payments.reduce((m, p) => m + p.amount, 0), 0);

  return {
    ...publicProfile(profile),
    invoices: invoices.map(({ payments, ...i }) => ({
      ...i,
      paidAmount: payments.reduce((m, p) => m + p.amount, 0),
    })),
    totals: { billed, paid, outstanding: Math.max(0, billed - paid) },
  };
}

/**
 * Set a new password for a student who cannot sign in.
 *
 * Stamps passwordChangedAt so refresh tokens issued before the reset stop
 * working: whoever was signed in as them is signed out rather than carrying on
 * with a session the new password was meant to end.
 */
/**
 * Gives a login to someone registered without one: a real email in place of
 * the placeholder, a password, and the flag flipped. Refused on an account
 * that already has a login — that is a password reset, not a creation.
 */
export async function createStudentLogin(profileId: string, email: string, password: string, propertyId?: string) {
  const profile = await findStudentOrThrow(profileId, propertyId);
  const user = await prismaUnscoped.user.findUnique({ where: { id: profile.userId }, select: { hasLogin: true } });
  if (!user || user.hasLogin) throw new ConflictError('This account already has a login; reset the password instead');
  // Emails are unique across every tenant, so the check is unscoped too.
  const taken = await prismaUnscoped.user.findUnique({ where: { email }, select: { id: true } });
  if (taken) throw new ConflictError('That email is already in use');
  await db.user.update({
    where: { id: profile.userId },
    data: { email, passwordHash: await hashPassword(password), hasLogin: true, passwordChangedAt: new Date() },
  });
}

export async function resetStudentPassword(
  profileId: string,
  newPassword: string,
  propertyId?: string,
) {
  // Reuses the tenant and property scoping, so a student outside the caller's
  // property is unreachable here too.
  const profile = await findStudentOrThrow(profileId, propertyId);

  await db.user.update({
    where: { id: profile.userId },
    data: {
      passwordHash: await hashPassword(newPassword),
      passwordChangedAt: new Date(),
    },
  });
}

/**
 * A student replacing their own photo.
 *
 * Scoped by the signed-in user rather than an id from the client, so a student
 * can only ever reach their own record.
 */
export async function updateMyPhoto(userId: string, photoUrl: string | null) {
  const profile = await db.studentProfile.findFirst({ where: { userId } });
  if (!profile) throw new NotFoundError('Student not found');

  await db.studentProfile.update({
    where: { id: profile.id },
    data: { photoUrl },
  });

  // Re-read through getMyProfile rather than returning the staff-shaped
  // include: this answers the student's own client, which expects the bed's
  // room to carry its property.
  return getMyProfile(userId);
}

/**
 * Correct a student's details. Name and phone live on the User, the guardian
 * fields and document keys on the profile, so this writes both in one
 * transaction rather than leaving the two half-updated.
 */
export async function updateStudent(
  profileId: string,
  input: UpdateStudentInput,
  propertyId?: string,
) {
  // Reuses the scoping above, so an out-of-property id is unreachable here too.
  const existing = await findStudentOrThrow(profileId, propertyId);

  // Email is unique across every tenant, so a clash must be caught before the
  // write rather than surfacing as a constraint violation. prismaUnscoped
  // because the address being taken by another tenant's user still collides.
  if (input.email && input.email !== existing.user.email) {
    const taken = await prismaUnscoped.user.findUnique({ where: { email: input.email } });
    if (taken) throw new ConflictError('That email is already registered');
  }

  const userData = {
    ...(input.name !== undefined ? { name: input.name } : {}),
    ...(input.email !== undefined ? { email: input.email } : {}),
    ...(input.phone !== undefined ? { phone: input.phone } : {}),
  };
  const profileData = {
    ...(input.guardianName !== undefined ? { guardianName: input.guardianName } : {}),
    ...(input.guardianPhone !== undefined ? { guardianPhone: input.guardianPhone } : {}),
    ...(input.parentName !== undefined ? { parentName: input.parentName } : {}),
    ...(input.parentPhone !== undefined ? { parentPhone: input.parentPhone } : {}),
    ...(input.idProofUrl !== undefined ? { idProofUrl: input.idProofUrl } : {}),
    ...(input.photoUrl !== undefined ? { photoUrl: input.photoUrl } : {}),
    // The address, deposit, KYC and police fields. Every one of them was
    // validated by the schema and then dropped here, so an edit answered 200
    // while saving nothing.
    ...(await sealKyc(complianceData(input as Record<string, unknown>))),
    ...(await employeeData(input, profileId)),
  };

  const updated = await db.$transaction(async (tx) => {
    if (Object.keys(userData).length > 0) {
      await tx.user.update({ where: { id: existing.userId }, data: userData });
    }
    if (Object.keys(profileData).length > 0) {
      return tx.studentProfile.update({
        where: { id: profileId },
        data: profileData,
        include: studentInclude(),
      });
    }
    // Only user fields changed; re-read so the response still carries both.
    return tx.studentProfile.findFirstOrThrow({
      where: { id: profileId },
      include: studentInclude(),
    });
  });

  // Masked, like every other route that returns a student: this one answered
  // with the raw row, so an edit sent the full ID number back over the wire.
  return publicProfile(updated);
}

export async function assignBed(profileId: string, bedId: string, movedInAt?: Date) {
  const tenantId = currentTenantId();
  return db.$transaction(async (tx) => {
    const profile = await tx.studentProfile.findFirst({ where: { id: profileId } });
    if (!profile || profile.tenantId !== tenantId) throw new NotFoundError('Student not found');

    const bed = await tx.bed.findFirst({ where: { id: bedId, archivedAt: null }, include: { room: { select: { propertyId: true, floor: true } } } });
    if (!bed || bed.tenantId !== tenantId) throw new NotFoundError('Bed not found');
    if (bed.room.floor == null) throw new ConflictError('Set a floor for this room before assigning its beds');
    if (bed.status !== BedStatus.VACANT) throw new ConflictError('Bed is not vacant');

    if (profile.bedId && profile.bedId !== bedId) {
      await tx.bed.update({ where: { id: profile.bedId }, data: { status: BedStatus.VACANT } });
    }
    await tx.bed.update({ where: { id: bedId }, data: { status: BedStatus.OCCUPIED } });
    await reconcileRoomBilling(tx, profileId, bed.roomId);
    // Moving to a bed in another property moves the student with it.
    // Residency: a first bed, a return after moving out, or an explicit date
    // (re)starts it; a swap between beds keeps the original move-in day.
    const startsResidency = !profile.bedId || !profile.movedInAt || movedInAt !== undefined;
    return tx.studentProfile.update({
      where: { id: profileId },
      data: {
        bedId,
        propertyId: bed.room.propertyId,
        ...(startsResidency ? { movedInAt: movedInAt ?? new Date(), vacatedAt: null } : {}),
      },
      include: studentInclude(),
    });
  });
}

/** Enroll (or clear) a student's biometric id used by the terminals. */
export async function setBiometricId(profileId: string, biometricId: string | null) {
  const profile = await db.studentProfile.findFirst({ where: { id: profileId } });
  if (!profile) throw new NotFoundError('Student not found');
  if (biometricId) {
    const clash = await db.studentProfile.findFirst({ where: { biometricId, id: { not: profileId } } });
    if (clash) throw new ConflictError('That biometric id is already enrolled to another student');
  }
  return db.studentProfile.update({ where: { id: profileId }, data: { biometricId }, include: studentInclude() });
}

/**
 * A student's own profile: their room, who else is in it, what they have
 * paid as deposit and where their paperwork stands. The KYC number comes
 * back masked like everywhere else.
 */
export async function getMyProfile(userId: string) {
  const profile = await db.studentProfile.findFirst({
    where: { userId },
    include: {
      user: { select: { id: true, name: true, email: true, phone: true, hasLogin: true } },
      property: { select: { id: true, name: true, address: true, city: true, state: true, logoUrl: true, pricingMode: true, curfewTime: true } },
      bed: {
        include: {
          room: {
            include: {
              // Under ROOM pricing only one roommate is invoiced, so the
              // student needs to be told who — otherwise a ₹0 dues page looks
              // like a bug to everyone else in the room.
              property: { select: { name: true, city: true, pricingMode: true } },
              billedStudent: { select: { id: true, user: { select: { name: true } } } },
              // Roommates: names and bed labels only. No contact details —
              // those are the other student's to share.
              beds: {
                where: { archivedAt: null },
                orderBy: { label: 'asc' },
                include: { student: { select: { id: true, user: { select: { name: true } } } } },
              },
            },
          },
        },
      },
    },
  });
  if (!profile) throw new NotFoundError('No student profile for this account');
  const { bed, ...rest } = profile;
  return {
    ...publicProfile(rest),
    bed: bed
      ? {
          id: bed.id,
          label: bed.label,
          status: bed.status,
          monthlyRent: bed.monthlyRent,
          room: {
            id: bed.room.id,
            number: bed.room.number,
            floor: bed.room.floor,
            type: bed.room.type,
            notes: bed.room.notes,
            monthlyRent: bed.room.monthlyRent,
            property: bed.room.property,
            billedStudent: bed.room.billedStudent,
            beds: bed.room.beds.map((b) => ({
              id: b.id,
              label: b.label,
              status: b.status,
              occupant: b.student ? { id: b.student.id, name: b.student.user.name, isMe: b.student.id === profile.id } : null,
            })),
          },
        }
      : null,
  };
}

/** The fields a student may correct themselves. Everything about money,
 *  verification or the bed stays with the warden. */
export async function updateMyProfile(
  userId: string,
  input: {
    guardianName?: string | null;
    guardianPhone?: string | null;
    parentName?: string | null;
    parentPhone?: string | null;
    address?: string | null;
    city?: string | null;
    state?: string | null;
    postalCode?: string | null;
    photoUrl?: string | null;
  },
) {
  const tenantId = getTenantIdOrThrow();
  const profile = await db.studentProfile.findFirst({ where: { userId } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  // A photo key must be one of THIS tenant's student photos: a student cannot
  // point their profile at someone else's file.
  if (input.photoUrl && !input.photoUrl.startsWith(`tenants/${tenantId}/students/photo/`)) {
    throw new BadRequestError('That photo does not belong to this account');
  }
  await db.studentProfile.update({ where: { id: profile.id }, data: input });
  return getMyProfile(userId);
}

export type MyDoc = 'photo' | 'idProof' | 'addressProof' | 'policeVerification' | 'propertyLogo';

/** The S3 key of one of the student's own documents, or null if none. */
export async function myDocKey(userId: string, doc: MyDoc): Promise<string | null> {
  const profile = await db.studentProfile.findFirst({
    where: { userId },
    select: { photoUrl: true, idProofUrl: true, kycAddressProofUrl: true, policeVerificationDocUrl: true, property: { select: { logoUrl: true } } },
  });
  if (!profile) throw new NotFoundError('No student profile for this account');
  return (
    {
      photo: profile.photoUrl,
      idProof: profile.idProofUrl,
      addressProof: profile.kycAddressProofUrl,
      policeVerification: profile.policeVerificationDocUrl,
      // The hostel's own logo, so the student's pages can carry it.
      propertyLogo: profile.property?.logoUrl,
    }[doc] ?? null
  );
}
