import { BedStatus, InvoiceLineKind, InvoiceType, Prisma, RateBasis, StayStatus } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { assignBed } from '../students/students.service';
import { paginated, type Pagination } from '../../lib/pagination';
import { NO_LOGIN_EMAIL_DOMAIN } from '../../lib/no-login';
import { applyStayTax, taxedTotal } from './stays-tax';
import { bookedStayCutoffForDay, bookingStartsBeforeToday, findOverlappingStay, heldUntil } from './stays-overlap';

/**
 * Stays (dormitories).
 *
 * A dormitory sells nights, not months: a customer is booked into a bed from
 * a planned check-in to a planned check-out, the stay is invoiced up front
 * when the room charges per night, and the office records the actual check-in
 * and check-out. Arriving before the property's standard check-in time or
 * leaving after its check-out time can carry a surcharge; staying past the
 * planned date adds nights. Everything a hostel does today is untouched: a
 * stay is only created when the caller sends check-in and check-out times.
 */

const DAY = 86_400_000;
const dayOf = (d: Date) => Math.floor(d.getTime() / DAY);
const ymd = (d: Date) => d.toISOString().slice(0, 10);

/** Calendar nights between two instants; at least one. */
export function nightsBetween(checkIn: Date, checkOut: Date): number {
  return Math.max(1, dayOf(checkOut) - dayOf(checkIn));
}

/** The property's standard time on the planned day, as an instant (IST). */
function standardAt(day: Date, hhmm: string): Date {
  return new Date(`${ymd(day)}T${hhmm}:00+05:30`);
}

const stayInclude = {
  student: { select: { id: true, user: { select: { name: true, email: true, phone: true } } } },
  bed: { select: { id: true, label: true, room: { select: { id: true, number: true, floor: true, propertyId: true } } } },
} as const;

async function rateFor(bedId: string): Promise<{ basis: RateBasis; rate: number; propertyId: string }> {
  const bed = await db.bed.findFirst({ where: { id: bedId }, include: { room: { select: { rateBasis: true, nightlyRent: true, propertyId: true } } } });
  if (!bed) throw new NotFoundError('Bed not found');
  return { basis: bed.room.rateBasis, rate: bed.nightlyRent ?? bed.room.nightlyRent ?? 0, propertyId: bed.room.propertyId };
}

/** One-line invoice for a stay or a surcharge, in the month of the check-in. */
async function raiseInvoice(propertyId: string, studentProfileId: string, type: InvoiceType, periodMonth: string, label: string, amount: number, dueDate: Date, coveredFrom?: Date, coveredTo?: Date) {
  const tenantId = getTenantIdOrThrow();
  // One RENT invoice per student per month is the schema's rule; a second
  // stay in the same month lands as OTHER so it cannot collide.
  let kind = type;
  if (type === InvoiceType.RENT) {
    const clash = await db.invoice.findFirst({ where: { studentProfileId, type: InvoiceType.RENT, periodMonth }, select: { id: true } });
    if (clash) kind = InvoiceType.OTHER;
  }
  if (kind === InvoiceType.OTHER) {
    const clash = await db.invoice.findFirst({ where: { studentProfileId, type: InvoiceType.OTHER, periodMonth }, select: { id: true, amount: true } });
    if (clash) {
      // Fold the line into the month's existing OTHER invoice rather than fail.
      await db.invoiceLine.create({ data: { tenantId, invoiceId: clash.id, kind: InvoiceLineKind.CHARGE, label, amount } });
      await db.invoice.update({ where: { id: clash.id }, data: { amount: clash.amount + amount } });
      await applyStayTax(clash.id, propertyId);
      return clash.id;
    }
  }
  const inv = await db.invoice.create({
    data: {
      tenantId,
      studentProfileId,
      type: kind,
      periodMonth,
      cycleMonths: 1,
      amount,
      dueDate,
      coveredFrom,
      coveredTo,
      lines: { create: [{ tenantId, kind: kind === InvoiceType.RENT ? InvoiceLineKind.RENT : InvoiceLineKind.CHARGE, label, amount }] },
    },
    select: { id: true },
  });
  await applyStayTax(inv.id, propertyId);
  return inv.id;
}

const OPEN = [StayStatus.BOOKED, StayStatus.CHECKED_IN];

const whenIST = (d: Date) => d.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });

/**
 * Which beds are free for a whole window, for planning a booking: every bed
 * of the property, marked free or taken, and when taken, why — the stay in
 * the way, a hold, or someone in it the hostel way without a stay.
 */
/**
 * `detail` (Sprint L3) adds each bed's label, room number, extra-bed flag and
 * nightly rate, so group check-in can name and price the free beds without
 * downloading every room; without it the reply is as before.
 */
export async function availabilityFor(from: Date, to: Date, propertyId?: string, detail = false) {
  if (to <= from) throw new BadRequestError('Check-out must be after check-in');
  const now = new Date();
  if (bookingStartsBeforeToday(from, now)) throw new BadRequestError('Check-in cannot be on a past date');
  if (to <= now) throw new BadRequestError('Check-out must be in the future');
  const beds = await db.bed.findMany({
    where: { archivedAt: null, room: { floor: { not: null }, ...(propertyId ? { propertyId } : {}) } },
    select: { id: true, label: true, status: true, roomId: true, isExtra: true, nightlyRent: true, room: { select: { number: true, floor: true, rateBasis: true, nightlyRent: true } }, student: { select: { user: { select: { name: true } } } } },
    orderBy: [{ room: { number: 'asc' } }, { label: 'asc' }],
  });
  const about = (b: (typeof beds)[number]) => (detail ? { label: b.label, roomNumber: b.room.number, isExtra: b.isExtra, rate: b.room.rateBasis === 'DAILY' ? b.nightlyRent ?? b.room.nightlyRent ?? 0 : 0 } : {});
  const open = await db.stay.findMany({
    where: { bedId: { in: beds.map((b) => b.id) }, status: { in: OPEN }, plannedCheckIn: { lt: to } },
    include: stayInclude,
    orderBy: { plannedCheckIn: 'asc' },
  });
  const clashes = new Map<string, (typeof open)[number]>();
  for (const st of open) if (heldUntil(st, now) > from && !clashes.has(st.bedId)) clashes.set(st.bedId, st);
  const checkedIn = new Set(open.filter((st) => st.status === StayStatus.CHECKED_IN).map((st) => st.bedId));
  const list = beds.map((b) => {
    const clash = clashes.get(b.id) ?? null;
    if (clash) return { bedId: b.id, roomId: b.roomId, free: false as const, reason: 'clash' as const, clash, ...about(b) };
    if (b.status === BedStatus.RESERVED) return { bedId: b.id, roomId: b.roomId, free: false as const, reason: 'hold' as const, clash: null, ...about(b) };
    if (b.status === BedStatus.OCCUPIED && b.student && !checkedIn.has(b.id)) return { bedId: b.id, roomId: b.roomId, free: false as const, reason: 'occupied' as const, clash: null, occupant: b.student.user.name, ...about(b) };
    return { bedId: b.id, roomId: b.roomId, free: true as const, reason: null, clash: null, ...about(b) };
  });
  return { from, to, free: list.filter((b) => b.free).length, beds: list };
}

/** The open stays on a bed whose window overlaps [from, to). */
async function clashesOn(bedId: string, from: Date, to: Date, ignoreId?: string) {
  const now = new Date();
  const open = await db.stay.findMany({
    where: { bedId, ...(ignoreId ? { id: { not: ignoreId } } : {}), status: { in: OPEN }, plannedCheckIn: { lt: to } },
    include: stayInclude,
    orderBy: { plannedCheckIn: 'asc' },
  });
  // Keep the ID check here as well: an edit target must never be considered a
  // collision even if a query implementation or fixture returns it.
  return open.filter((st) => st.id !== ignoreId && heldUntil(st, now) > from);
}

/**
 * Book a bed for a window. A bed can hold several bookings in a day as long
 * as their windows never overlap — a walk-in can have it from noon to three
 * ahead of a guest arriving at seven — so the clash check is on time, not
 * on the bed's live status. The bed itself is only taken at check-in.
 *
 * The charge is nights × the bed's nightly rate, or a figure of the office's
 * own (`amount`) for an hourly use or a negotiated price.
 */
export async function createStay(input: { studentProfileId: string; bedId: string; checkIn: Date; checkOut: Date; note?: string; amount?: number }, actorId: string) {
  const tenantId = getTenantIdOrThrow();
  const now = new Date();
  if (input.checkOut <= input.checkIn) throw new BadRequestError('Check-out must be after check-in');
  if (bookingStartsBeforeToday(input.checkIn, now)) throw new BadRequestError('Check-in cannot be on a past date');
  if (input.checkOut <= now) throw new BadRequestError('Check-out must be in the future');
  // One person cannot be in two places at once: their own open stays must
  // not overlap the new window either.
  const theirs = await db.stay.findMany({ where: { studentProfileId: input.studentProfileId, status: { in: OPEN }, plannedCheckIn: { lt: input.checkOut } }, select: { id: true, status: true, plannedCheckOut: true, bed: { select: { label: true, room: { select: { number: true } } } } } });
  const mine = findOverlappingStay(theirs, input.checkIn);
  if (mine) throw new ConflictError(`This customer already has a stay in room ${mine.bed.room.number}, bed ${mine.bed.label} over those times; check them out or cancel it first`);

  const bed = await db.bed.findFirst({ where: { id: input.bedId, archivedAt: null }, select: { status: true, room: { select: { floor: true } }, student: { select: { user: { select: { name: true } } } } } });
  if (!bed) throw new NotFoundError('Bed not found');
  if (bed.room.floor == null) throw new ConflictError('Set a floor for this room before booking its beds');
  const clash = (await clashesOn(input.bedId, input.checkIn, input.checkOut))[0];
  if (clash) throw new ConflictError(`${clash.student.user.name} has this bed from ${whenIST(clash.plannedCheckIn)} to ${whenIST(clash.plannedCheckOut)}${clash.status === StayStatus.CHECKED_IN ? ' (checked in)' : ''}; pick a window around that`);
  // A bed taken the hostel way (no stay) or put on hold is not bookable.
  if (bed.status === BedStatus.RESERVED) throw new ConflictError('This bed is on hold; release it first');
  if (bed.status === BedStatus.OCCUPIED && bed.student && !(await db.stay.findFirst({ where: { bedId: input.bedId, status: StayStatus.CHECKED_IN }, select: { id: true } }))) {
    throw new ConflictError(`${bed.student.user.name} is in this bed without a stay; move them out first`);
  }

  const { basis, rate, propertyId } = await rateFor(input.bedId);
  const nights = nightsBetween(input.checkIn, input.checkOut);
  const amountOverridden = input.amount !== undefined;
  const amount = amountOverridden ? input.amount! : basis === RateBasis.DAILY ? nights * rate : 0;

  let invoiceId: string | null = null;
  if (amount > 0) {
    const label = amountOverridden
      ? `Stay · ${whenIST(input.checkIn)} to ${whenIST(input.checkOut)} (custom charge)`
      : `Stay · ${nights} night${nights === 1 ? '' : 's'} × ₹${rate.toLocaleString('en-IN')} (${ymd(input.checkIn)} to ${ymd(input.checkOut)})`;
    invoiceId = await raiseInvoice(propertyId, input.studentProfileId, InvoiceType.RENT, ymd(input.checkIn).slice(0, 7), label, amount, input.checkIn, input.checkIn, input.checkOut);
  }
  return db.stay.create({
    data: { tenantId, studentProfileId: input.studentProfileId, bedId: input.bedId, propertyId, plannedCheckIn: input.checkIn, plannedCheckOut: input.checkOut, nights, ratePerNight: rate, amount, amountOverridden, invoiceId, note: input.note, createdById: actorId },
    include: stayInclude,
  });
}

async function loadStay(id: string) {
  const stay = await db.stay.findFirst({ where: { id }, include: stayInclude });
  if (!stay) throw new NotFoundError('Stay not found');
  return stay;
}

/**
 * Record the arrival. `early` defaults to "before the standard check-in time
 * on the planned day"; the office can override either way. An early arrival
 * is charged the property's early check-in fee when one is set.
 */
export async function checkIn(id: string, input: { at?: Date; early?: boolean }) {
  const stay = await loadStay(id);
  if (stay.status !== StayStatus.BOOKED) throw new ConflictError('This stay is not awaiting check-in');
  const at = input.at ?? new Date();
  // The bed is taken now, not at booking: whoever is still in it must leave first.
  const inBed = await db.stay.findFirst({ where: { bedId: stay.bedId, status: StayStatus.CHECKED_IN }, include: stayInclude });
  if (inBed) throw new ConflictError(`${inBed.student.user.name} is still in this bed (planned out ${whenIST(inBed.plannedCheckOut)}); check them out first`);
  await assignBed(stay.studentProfileId, stay.bedId, at);
  const property = await db.property.findFirst({ where: { id: stay.propertyId }, select: { checkInTime: true, earlyCheckInCharge: true } });
  const standard = standardAt(stay.plannedCheckIn, property?.checkInTime ?? '12:00');
  const early = input.early ?? at < standard;
  let earlyInvoiceId: string | null = null;
  if (early && (property?.earlyCheckInCharge ?? 0) > 0) {
    earlyInvoiceId = await raiseInvoice(stay.propertyId, stay.studentProfileId, InvoiceType.OTHER, ymd(at).slice(0, 7), `Early check-in · ${at.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' })}`, property!.earlyCheckInCharge, at);
  }
  return db.stay.update({ where: { id }, data: { status: StayStatus.CHECKED_IN, actualCheckIn: at, earlyCheckIn: early, earlyInvoiceId }, include: stayInclude });
}

/**
 * Record the departure and free the bed. `late` defaults to "after the
 * standard check-out time on the planned day". A late departure is charged
 * the late check-out fee; departing on a later day than planned adds the
 * extra nights at the stay's rate.
 */
export async function checkOut(id: string, input: { at?: Date; late?: boolean }) {
  const stay = await loadStay(id);
  if (stay.status !== StayStatus.CHECKED_IN) throw new ConflictError('This stay is not checked in');
  const at = input.at ?? new Date();
  const property = await db.property.findFirst({ where: { id: stay.propertyId }, select: { checkOutTime: true, lateCheckOutCharge: true } });
  const standard = standardAt(stay.plannedCheckOut, property?.checkOutTime ?? '11:00');
  const late = input.late ?? at > standard;
  const extraNights = Math.max(0, dayOf(at) - dayOf(stay.plannedCheckOut));
  let lateInvoiceId: string | null = null;
  const period = ymd(at).slice(0, 7);
  if (extraNights > 0 && stay.ratePerNight > 0) {
    lateInvoiceId = await raiseInvoice(stay.propertyId, stay.studentProfileId, InvoiceType.OTHER, period, `Extended stay · ${extraNights} extra night${extraNights === 1 ? '' : 's'} × ₹${stay.ratePerNight.toLocaleString('en-IN')}`, extraNights * stay.ratePerNight, at);
  }
  if (late && (property?.lateCheckOutCharge ?? 0) > 0) {
    lateInvoiceId = await raiseInvoice(stay.propertyId, stay.studentProfileId, InvoiceType.OTHER, period, `Late check-out · ${at.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' })}`, property!.lateCheckOutCharge, at);
  }
  // Free the bed directly: a per-night stay has no monthly invoice to credit.
  await db.$transaction(async (tx) => {
    const profile = await tx.studentProfile.findFirst({ where: { id: stay.studentProfileId }, select: { bedId: true } });
    if (profile?.bedId === stay.bedId) {
      await tx.bed.update({ where: { id: stay.bedId }, data: { status: BedStatus.VACANT } });
      await tx.room.updateMany({ where: { billedStudentProfileId: stay.studentProfileId }, data: { billedStudentProfileId: null } });
      await tx.studentProfile.update({ where: { id: stay.studentProfileId }, data: { bedId: null, vacatedAt: at } });
    }
  });
  return db.stay.update({ where: { id }, data: { status: StayStatus.CHECKED_OUT, actualCheckOut: at, lateCheckOut: late, lateInvoiceId, nights: stay.nights + extraNights }, include: stayInclude });
}

/**
 * Bring the stay's rent invoice in line with a new charge. One line on its
 * own invoice is rewritten; a line folded into a shared charges invoice gets
 * an adjustment line instead, so the other charges on it are untouched.
 * Money already taken caps how low the charge can go.
 */
async function reconcileStayInvoice(
  stay: { id: string; studentProfileId: string; invoiceId: string | null; plannedCheckIn: Date; plannedCheckOut: Date; nights: number; ratePerNight: number; amount: number },
  newAmount: number,
  label: string,
  propertyId: string,
) {
  const tenantId = getTenantIdOrThrow();
  if (!stay.invoiceId) {
    if (newAmount <= 0) return null;
    return raiseInvoice(propertyId, stay.studentProfileId, InvoiceType.RENT, ymd(stay.plannedCheckIn).slice(0, 7), label, newAmount, stay.plannedCheckIn, stay.plannedCheckIn, stay.plannedCheckOut);
  }
  const inv = await db.invoice.findFirst({ where: { id: stay.invoiceId }, include: { lines: true, payments: { where: { status: 'CLEARED' }, select: { amount: true } } } });
  if (!inv) return null;
  const paid = inv.payments.reduce((n, p) => n + p.amount, 0);
  // GST lines follow the rest (applyStayTax), so they are not the stay's own.
  const own = inv.lines.filter((l) => l.kind !== InvoiceLineKind.GST);
  const base = own.reduce((n, l) => n + l.amount, 0);
  // The stay's share moves from its old charge to the new one; the rest of a
  // shared charges invoice stays as it is.
  const single = own.length <= 1;
  const newBase = single ? newAmount : base + (newAmount - stay.amount);
  const newTotal = await taxedTotal(propertyId, newBase);
  if (paid > newTotal) throw new ConflictError(`₹${paid.toLocaleString('en-IN')} has already been collected on this stay; the charge cannot drop below that without a refund`);
  if (single) {
    if (newAmount === 0 && paid === 0) {
      await db.invoice.delete({ where: { id: inv.id } });
      return null;
    }
    await db.invoice.update({ where: { id: inv.id }, data: { amount: newAmount, coveredFrom: stay.plannedCheckIn, coveredTo: stay.plannedCheckOut, status: paid >= newAmount ? 'PAID' : paid > 0 ? 'PARTIAL' : 'PENDING' } });
    if (own[0]) await db.invoiceLine.update({ where: { id: own[0].id }, data: { amount: newAmount, label } });
    else await db.invoiceLine.create({ data: { tenantId, invoiceId: inv.id, kind: InvoiceLineKind.RENT, label, amount: newAmount } });
    await applyStayTax(inv.id, propertyId);
    return inv.id;
  }
  const delta = newAmount - stay.amount;
  if (delta !== 0) {
    await db.invoiceLine.create({ data: { tenantId, invoiceId: inv.id, kind: InvoiceLineKind.CHARGE, label: `${label} · adjustment`, amount: delta } });
    const amount = inv.amount + delta;
    await db.invoice.update({ where: { id: inv.id }, data: { amount, status: paid >= amount ? 'PAID' : paid > 0 ? 'PARTIAL' : 'PENDING' } });
    await applyStayTax(inv.id, propertyId);
  }
  return inv.id;
}

/**
 * Change a booking: another bed, other times, a charge of the office's own,
 * a note. A booked stay can change everything; someone already checked in
 * can only have their check-out moved (and the note or charge). The clash
 * checks are the same as at booking, ignoring the stay itself, and the
 * rent invoice follows the new charge.
 */
export async function updateStay(id: string, input: { bedId?: string; checkIn?: Date; checkOut?: Date; amount?: number | null; note?: string | null }) {
  const stay = await loadStay(id);
  if (stay.status !== StayStatus.BOOKED && stay.status !== StayStatus.CHECKED_IN) throw new ConflictError('Only a booked or checked-in stay can be changed');
  if (stay.status === StayStatus.CHECKED_IN && ((input.bedId && input.bedId !== stay.bedId) || (input.checkIn && input.checkIn.getTime() !== stay.plannedCheckIn.getTime()))) {
    throw new ConflictError('They are already in the bed: only the check-out, the note or the charge can change now');
  }
  const bedId = input.bedId ?? stay.bedId;
  const checkIn = input.checkIn ?? stay.plannedCheckIn;
  const checkOut = input.checkOut ?? stay.plannedCheckOut;
  if (checkOut <= checkIn) throw new BadRequestError('Check-out must be after check-in');
  const now = new Date();
  if (input.checkIn && input.checkIn.getTime() !== stay.plannedCheckIn.getTime() && bookingStartsBeforeToday(input.checkIn, now)) throw new BadRequestError('Check-in cannot be moved to a past date');
  if (stay.status === StayStatus.BOOKED && checkOut <= now) throw new BadRequestError('Check-out must be in the future');

  const theirs = await db.stay.findMany({ where: { id: { not: id }, studentProfileId: stay.studentProfileId, status: { in: OPEN }, plannedCheckIn: { lt: checkOut } }, select: { id: true, status: true, plannedCheckOut: true, bed: { select: { label: true, room: { select: { number: true } } } } } });
  const mine = findOverlappingStay(theirs, checkIn, id);
  if (mine) throw new ConflictError(`This customer already has a stay in room ${mine.bed.room.number}, bed ${mine.bed.label} over those times`);
  const clash = (await clashesOn(bedId, checkIn, checkOut, id))[0];
  if (clash) throw new ConflictError(`${clash.student.user.name} has this bed from ${whenIST(clash.plannedCheckIn)} to ${whenIST(clash.plannedCheckOut)}${clash.status === StayStatus.CHECKED_IN ? ' (checked in)' : ''}; pick a window around that`);
  if (bedId !== stay.bedId) {
    const bed = await db.bed.findFirst({ where: { id: bedId, archivedAt: null }, select: { status: true, room: { select: { floor: true } }, student: { select: { user: { select: { name: true } } } } } });
    if (!bed) throw new NotFoundError('Bed not found');
    if (bed.room.floor == null) throw new ConflictError('Set a floor for this room before booking its beds');
    if (bed.status === BedStatus.RESERVED) throw new ConflictError('That bed is on hold; release it first');
    if (bed.status === BedStatus.OCCUPIED && bed.student && !(await db.stay.findFirst({ where: { bedId, status: StayStatus.CHECKED_IN }, select: { id: true } }))) {
      throw new ConflictError(`${bed.student.user.name} is in that bed without a stay; move them out first`);
    }
  }

  const { basis, rate, propertyId } = await rateFor(bedId);
  const nights = nightsBetween(checkIn, checkOut);
  // `amount: null` goes back to nights × rate; omitted keeps whatever rule the stay had.
  const amountOverridden = input.amount === null ? false : input.amount !== undefined ? true : stay.amountOverridden;
  // When only checkout changes, preserve a custom per-night rate rather than
  // freezing the old total. An explicit amount still wins.
  const previousCustomDaily = stay.nights > 0 ? stay.amount / stay.nights : stay.amount;
  const amount = amountOverridden ? (input.amount ?? Math.round(previousCustomDaily * nights)) : basis === RateBasis.DAILY ? nights * rate : 0;
  const label = amountOverridden
    ? `Stay · ${whenIST(checkIn)} to ${whenIST(checkOut)} (custom charge)`
    : `Stay · ${nights} night${nights === 1 ? '' : 's'} × ₹${rate.toLocaleString('en-IN')} (${ymd(checkIn)} to ${ymd(checkOut)})`;
  const invoiceId = await reconcileStayInvoice({ ...stay, plannedCheckIn: checkIn, plannedCheckOut: checkOut, nights, ratePerNight: rate }, amount, label, propertyId);
  return db.stay.update({
    where: { id },
    data: { bedId, propertyId, plannedCheckIn: checkIn, plannedCheckOut: checkOut, nights, ratePerNight: rate, amount, amountOverridden, invoiceId, ...(input.note !== undefined ? { note: input.note } : {}) },
    include: stayInclude,
  });
}

/**
 * A booking that never happened. It never held the bed, so nothing to give
 * back; its rent invoice is voided when nothing was paid on it, and left
 * for a refund when something was.
 */
export async function cancelStay(id: string) {
  const stay = await loadStay(id);
  if (stay.status !== StayStatus.BOOKED) throw new ConflictError('Only a booked stay can be cancelled');
  let invoiceId = stay.invoiceId;
  if (invoiceId) {
    const inv = await db.invoice.findFirst({ where: { id: invoiceId }, include: { lines: { select: { id: true, kind: true, amount: true } }, payments: { where: { status: 'CLEARED' }, select: { id: true } } } });
    if (inv && inv.payments.length === 0) {
      // GST lines follow the rest, so only the invoice's own lines count.
      const own = inv.lines.filter((l) => l.kind !== InvoiceLineKind.GST);
      const base = own.reduce((n, l) => n + l.amount, 0);
      if (own.length <= 1 || base - stay.amount <= 0) {
        // Its own invoice, or a shared one with nothing else left on it: gone.
        await db.invoice.delete({ where: { id: invoiceId } });
      } else {
        // Folded into the month's charges invoice: take the stay's charge back
        // off it and leave the other charges standing.
        await db.invoiceLine.create({ data: { tenantId: getTenantIdOrThrow(), invoiceId, kind: InvoiceLineKind.CHARGE, label: `Stay cancelled · ${whenIST(stay.plannedCheckIn)} to ${whenIST(stay.plannedCheckOut)}`, amount: -stay.amount } });
        await db.invoice.update({ where: { id: invoiceId }, data: { amount: inv.amount - stay.amount } });
        await applyStayTax(invoiceId, stay.propertyId);
      }
      invoiceId = null;
    }
  }
  // `cancelledAt` is introduced by the accompanying migration. The checked-in
  // generated client in older workspaces may predate that migration; CI and
  // deployment regenerate it from schema.prisma before building.
  const data = { status: StayStatus.CANCELLED, cancelledAt: new Date(), invoiceId } as unknown as Prisma.StayUpdateInput;
  return db.stay.update({ where: { id }, data, include: stayInclude });
}

export interface StayListFilters {
  status?: StayStatus;
  propertyId?: string;
  studentProfileId?: string;
  open?: boolean;
  /** Customer name, email or phone, case-insensitive. */
  q?: string;
  /** Planned check-in on or after this day (YYYY-MM-DD). */
  from?: string;
  /** Planned check-in on or before this day (YYYY-MM-DD). */
  to?: string;
  /** Only stays in these rooms — the bed map asks for the rooms on screen (Sprint L2). */
  roomIds?: string[];
}

/**
 * Where the stay's own rent invoice stands: what it billed, what has cleared
 * against it and what is still due. Early and late surcharges share a
 * month's OTHER invoice with other charges, so they are not folded in here —
 * the flags on the stay say they were raised.
 */
async function billingFor<T extends { invoiceId: string | null }>(stays: T[]) {
  const ids = [...new Set(stays.map((s) => s.invoiceId).filter((id): id is string => !!id))];
  if (ids.length === 0) return stays.map((s) => ({ ...s, billing: null }));
  const invoices = await db.invoice.findMany({
    where: { id: { in: ids } },
    select: { id: true, amount: true, status: true, payments: { where: { status: 'CLEARED' }, select: { amount: true } } },
  });
  const byId = new Map(invoices.map((inv) => {
    const paid = inv.payments.reduce((sum, p) => sum + p.amount, 0);
    return [inv.id, { invoiceId: inv.id, amount: inv.amount, paid, due: Math.max(0, inv.amount - paid), status: inv.status }];
  }));
  return stays.map((s) => ({ ...s, billing: s.invoiceId ? byId.get(s.invoiceId) ?? null : null }));
}

/** Rooms one bed-map request may name, and the stays it may return for them. */
export const ROOM_STAYS_ROOMS_MAX = 200;
const ROOM_STAYS_CAP = 5000;

export async function listStays(filters: StayListFilters, pagination?: Pagination | null) {
  const q = filters.q?.trim();
  const where = {
    ...(filters.open
      ? { OR: [{ status: StayStatus.CHECKED_IN }, { status: StayStatus.BOOKED, plannedCheckOut: { gt: new Date() } }] }
      : filters.status
        ? { status: filters.status }
        : {}),
    ...(filters.propertyId ? { propertyId: filters.propertyId } : {}),
    ...(filters.studentProfileId ? { studentProfileId: filters.studentProfileId } : {}),
    ...(filters.roomIds ? { bed: { roomId: { in: filters.roomIds } } } : {}),
    ...(filters.from || filters.to
      ? {
          plannedCheckIn: {
            ...(filters.from ? { gte: new Date(`${filters.from}T00:00:00+05:30`) } : {}),
            ...(filters.to ? { lt: new Date(new Date(`${filters.to}T00:00:00+05:30`).getTime() + DAY) } : {}),
          },
        }
      : {}),
    ...(q
      ? {
          student: {
            user: {
              OR: [
                { name: { contains: q, mode: 'insensitive' as const } },
                // A placeholder address is not something anyone would type to find a person.
                { AND: [{ email: { contains: q, mode: 'insensitive' as const } }, { email: { not: { endsWith: `@${NO_LOGIN_EMAIL_DOMAIN}` } } }] },
                { phone: { contains: q } },
              ],
            },
          },
        }
      : {}),
  };
  const orderBy = { plannedCheckIn: 'desc' as const };
  // The bed map's ask for the rooms on screen is bounded by those rooms, so it
  // gets every open stay in them rather than the newest 300 of the property.
  if (!pagination) return billingFor(await db.stay.findMany({ where, include: stayInclude, orderBy, take: filters.roomIds ? ROOM_STAYS_CAP : 300 }));
  const [items, total] = await Promise.all([db.stay.findMany({ where, include: stayInclude, orderBy, skip: pagination.skip, take: pagination.limit }), db.stay.count({ where })]);
  return paginated(await billingFor(items), total, pagination);
}

/**
 * The stays holding a bed on a given day: booked or checked in, planned to
 * arrive by the end of that day and to leave after it starts. Someone who
 * is checked in and past their planned check-out still holds the bed until
 * they actually leave, so for today and earlier an overstay counts too.
 */
export async function occupancyOn(dateStr: string, propertyId?: string) {
  const start = new Date(`${dateStr}T00:00:00+05:30`), end = new Date(start.getTime() + DAY);
  const now = new Date();
  const pastOrToday = start <= now;
  const bookedCutoff = bookedStayCutoffForDay(start, end, now);
  const stays = await db.stay.findMany({
    where: {
      ...(propertyId ? { propertyId } : {}),
      plannedCheckIn: { lt: end },
      OR: [
        { status: StayStatus.BOOKED, plannedCheckOut: { gt: bookedCutoff } },
        { status: StayStatus.CHECKED_IN, ...(pastOrToday ? {} : { plannedCheckOut: { gt: start } }) },
      ],
    },
    include: stayInclude,
    orderBy: { plannedCheckIn: 'asc' },
  });
  return { date: dateStr, stays };
}

/** Arrivals and departures due on a day, for the front desk. */
export async function dayBoard(dateStr: string, propertyId?: string) {
  const start = new Date(`${dateStr}T00:00:00+05:30`), end = new Date(start.getTime() + DAY);
  const where = propertyId ? { propertyId } : {};
  const [arrivals, departures, inHouse] = await Promise.all([
    db.stay.findMany({ where: { ...where, status: StayStatus.BOOKED, plannedCheckIn: { gte: start, lt: end } }, include: stayInclude, orderBy: { plannedCheckIn: 'asc' } }),
    db.stay.findMany({ where: { ...where, status: StayStatus.CHECKED_IN, plannedCheckOut: { lt: end } }, include: stayInclude, orderBy: { plannedCheckOut: 'asc' } }),
    db.stay.count({ where: { ...where, status: StayStatus.CHECKED_IN } }),
  ]);
  return { date: dateStr, arrivals, departures, inHouse };
}
