import { AssetCheckPhase, BedStatus, InvoiceLineKind, InvoiceStatus, InvoiceType, MoveOutStatus, PaymentStatus, Prisma, StayStatus, StudentRequestType } from '@prisma/client';
import { paginated, type Pagination } from '../../lib/pagination';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { cycleSpan, utcDay } from '../billing/billing-rules.service';
import { vacateBed } from '../students/students.service';

/**
 * Move-out and settlement (Sprint 4).
 *
 * The loudest complaint against Indian hostels is a deposit that vanishes
 * into silence. This module makes leaving a dated, visible process: notice
 * → room checklist → settlement draft → shared with the student → refund
 * recorded → bed freed. Every number in the settlement comes from things the
 * hostel already records (deposit, invoices, payments, pro-rata, checklist),
 * and the refund is never negative — a shortfall becomes a final invoice.
 *
 * Nothing here changes an old client: residency is a new field, the
 * existing "move out of bed" still works, and students without a move-out
 * see exactly what they saw before.
 */

const DAY_MS = 86_400_000;
const dayOnly = (d: Date) => new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
const todayUtc = () => dayOnly(new Date());

// ── Asset templates and checks ─────────────────────────────────────────────

export interface AssetItem {
  key: string;
  name: string;
  /** What is charged when the item is missing or broken at move-out. */
  charge: number;
}
export interface CheckedItem extends AssetItem {
  ok: boolean;
  note?: string | null;
  photoKey?: string | null;
}

export const DEFAULT_ASSET_ITEMS: AssetItem[] = [
  { key: 'bed', name: 'Bed frame', charge: 2500 },
  { key: 'mattress', name: 'Mattress', charge: 1500 },
  { key: 'fan', name: 'Ceiling fan', charge: 1800 },
  { key: 'light', name: 'Tube light / bulb', charge: 300 },
  { key: 'lock', name: 'Door lock & keys', charge: 500 },
  { key: 'chair', name: 'Chair', charge: 800 },
  { key: 'table', name: 'Study table', charge: 1500 },
  { key: 'cupboard', name: 'Cupboard', charge: 2500 },
  { key: 'window', name: 'Window & curtain', charge: 700 },
  { key: 'walls', name: 'Walls & paint', charge: 1000 },
];

function normaliseItems(items: AssetItem[]): AssetItem[] {
  const seen = new Set<string>();
  return items
    .map((i) => ({ key: i.key.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '_').slice(0, 40), name: i.name.trim().slice(0, 60), charge: Math.max(0, Math.floor(i.charge)) }))
    .filter((i) => i.key && i.name && !seen.has(i.key) && seen.add(i.key));
}

/** The checklist for a room type, falling back to the property default, then the built-in list. */
export async function getAssetTemplate(propertyId: string, roomType?: string | null) {
  const rows = await db.roomAssetTemplate.findMany({ where: { propertyId, roomType: { in: [roomType ?? '', ''] } } });
  const specific = roomType ? rows.find((r) => r.roomType === roomType) : undefined;
  const fallback = rows.find((r) => r.roomType === '');
  const row = specific ?? fallback;
  return { propertyId, roomType: roomType ?? '', items: (row?.items as unknown as AssetItem[]) ?? DEFAULT_ASSET_ITEMS, source: specific ? 'room-type' : fallback ? 'property' : 'default', updatedAt: row?.updatedAt ?? null };
}

export async function listAssetTemplates(propertyId: string) {
  const rows = await db.roomAssetTemplate.findMany({ where: { propertyId }, orderBy: { roomType: 'asc' } });
  return rows.map((r) => ({ roomType: r.roomType, items: r.items as unknown as AssetItem[], updatedAt: r.updatedAt }));
}

export async function putAssetTemplate(propertyId: string, roomType: string, items: AssetItem[]) {
  const tenantId = getTenantIdOrThrow();
  const property = await db.property.findFirst({ where: { id: propertyId }, select: { id: true } });
  if (!property) throw new NotFoundError('Property not found');
  const clean = normaliseItems(items);
  if (clean.length === 0) throw new BadRequestError('A checklist needs at least one item');
  const row = await db.roomAssetTemplate.upsert({
    where: { propertyId_roomType: { propertyId, roomType } },
    create: { tenantId, propertyId, roomType, items: clean as unknown as Prisma.InputJsonValue },
    update: { items: clean as unknown as Prisma.InputJsonValue },
  });
  return { roomType: row.roomType, items: row.items as unknown as AssetItem[], updatedAt: row.updatedAt };
}

async function studentWithRoom(studentProfileId: string) {
  const s = await db.studentProfile.findFirst({
    where: { id: studentProfileId },
    include: { user: { select: { id: true, name: true, email: true, phone: true } }, bed: { include: { room: { select: { id: true, number: true, type: true, propertyId: true } } } }, property: { select: { id: true, name: true, noticeDays: true, refundDays: true, prorataEnabled: true } } },
  });
  if (!s) throw new NotFoundError('Student not found');
  return s;
}

/** The latest check of each phase for a student. */
export async function listAssetChecks(studentProfileId: string) {
  const rows = await db.roomAssetCheck.findMany({ where: { studentProfileId }, orderBy: { checkedAt: 'desc' } });
  const pick = (phase: AssetCheckPhase) => rows.find((r) => r.phase === phase) ?? null;
  const shape = (r: (typeof rows)[number] | null) => (r ? { id: r.id, phase: r.phase, items: r.items as unknown as CheckedItem[], checkedAt: r.checkedAt, checkedById: r.checkedById, moveOutId: r.moveOutId } : null);
  return { in: shape(pick(AssetCheckPhase.IN)), out: shape(pick(AssetCheckPhase.OUT)) };
}

/**
 * Record a walk-through. At move-out, every item that was fine at move-in
 * and is not now becomes a proposed deduction at the template's charge; the
 * settlement editor starts from that list.
 */
export async function recordAssetCheck(studentProfileId: string, phase: AssetCheckPhase, items: CheckedItem[], checkedById: string) {
  const tenantId = getTenantIdOrThrow();
  const s = await studentWithRoom(studentProfileId);
  const template = await getAssetTemplate(s.propertyId ?? s.bed?.room.propertyId ?? '', s.bed?.room.type ?? null);
  const byKey = new Map(template.items.map((t) => [t.key, t]));
  const clean: CheckedItem[] = items.map((i) => {
    const t = byKey.get(i.key);
    return { key: i.key, name: (t?.name ?? i.name ?? i.key).slice(0, 60), charge: Math.max(0, Math.floor(i.charge ?? t?.charge ?? 0)), ok: !!i.ok, note: i.note?.slice(0, 200) ?? null, photoKey: i.photoKey?.slice(0, 500) ?? null };
  });
  if (clean.length === 0) throw new BadRequestError('Tick at least one item');

  const active = await db.moveOut.findFirst({ where: { studentProfileId, status: { in: [MoveOutStatus.NOTICE, MoveOutStatus.CHECKLIST, MoveOutStatus.DRAFT] } } });
  const row = await db.roomAssetCheck.create({
    data: { tenantId, studentProfileId, phase, items: clean as unknown as Prisma.InputJsonValue, checkedById, moveOutId: phase === AssetCheckPhase.OUT ? active?.id ?? null : null },
  });
  let proposedDeductions: Deduction[] = [];
  if (phase === AssetCheckPhase.OUT) {
    const checks = await listAssetChecks(studentProfileId);
    proposedDeductions = proposeDeductions(checks.in?.items ?? null, clean);
    if (active && active.status === MoveOutStatus.NOTICE) await db.moveOut.update({ where: { id: active.id }, data: { status: MoveOutStatus.CHECKLIST } });
  }
  return { check: { id: row.id, phase, items: clean, checkedAt: row.checkedAt }, proposedDeductions };
}

export interface Deduction {
  label: string;
  amount: number;
  note?: string | null;
  photoKey?: string | null;
  fromCheck?: boolean;
}

/** Items fine at move-in (or never checked in) and not fine at move-out. */
export function proposeDeductions(inItems: CheckedItem[] | null, outItems: CheckedItem[]): Deduction[] {
  const inOk = new Map((inItems ?? []).map((i) => [i.key, i.ok]));
  return outItems
    .filter((o) => !o.ok && (inItems === null || inOk.get(o.key) !== false) && o.charge > 0)
    .map((o) => ({ label: o.name, amount: o.charge, note: o.note ?? null, photoKey: o.photoKey ?? null, fromCheck: true }));
}

// ── Move-outs ──────────────────────────────────────────────────────────────

const moveOutInclude = {
  student: { include: { user: { select: { id: true, name: true, email: true, phone: true } }, bed: { include: { room: { select: { number: true, type: true } } } } } },
  settlement: true,
  property: { select: { id: true, name: true, noticeDays: true, refundDays: true } },
} as const;
type MoveOutRow = Prisma.MoveOutGetPayload<{ include: typeof moveOutInclude }>;

export function publicMoveOut(m: MoveOutRow) {
  const s = m.settlement;
  const today = todayUtc();
  return {
    id: m.id,
    studentProfileId: m.studentProfileId,
    student: { id: m.student.id, name: m.student.user.name, email: m.student.user.email, phone: m.student.user.phone, room: m.student.bed ? `Room ${m.student.bed.room.number} · Bed ${m.student.bed.label}` : null, bedId: m.student.bedId, depositPaid: m.student.depositPaid, depositRefunded: m.student.depositRefunded },
    property: m.property,
    noticeDate: m.noticeDate,
    lastDay: m.lastDay,
    startedBy: m.startedBy,
    reason: m.reason,
    status: m.status,
    daysToGo: Math.round((dayOnly(m.lastDay).getTime() - today.getTime()) / DAY_MS),
    settlement: s ? publicSettlement(s, today) : null,
    createdAt: m.createdAt,
    updatedAt: m.updatedAt,
  };
}

function publicSettlement(s: NonNullable<MoveOutRow['settlement']>, today = todayUtc()) {
  return {
    id: s.id,
    depositHeld: s.depositHeld,
    duesBalance: s.duesBalance,
    prorataCredit: s.prorataCredit,
    deductions: s.deductions as unknown as Deduction[],
    deductionsTotal: s.deductionsTotal,
    refundDue: s.refundDue,
    shortfall: s.shortfall,
    shortfallInvoiceId: s.shortfallInvoiceId,
    promisedDate: s.promisedDate,
    notes: s.notes,
    sharedAt: s.sharedAt,
    refundedAt: s.refundedAt,
    refundAmount: s.refundAmount,
    refundMethod: s.refundMethod,
    refundReference: s.refundReference,
    disputeRequestId: s.disputeRequestId,
    pdfKey: s.pdfKey,
    /** Promised date passed, money not yet returned. */
    overdue: !s.refundedAt && dayOnly(s.promisedDate).getTime() < today.getTime(),
  };
}

/** The arithmetic every screen shows, from the live books. */
export async function settlementPreview(studentProfileId: string, lastDay: Date) {
  const s = await studentWithRoom(studentProfileId);
  const depositHeld = Math.max(0, s.depositPaid - s.depositRefunded);
  const open = await db.invoice.findMany({
    where: { studentProfileId, status: { not: InvoiceStatus.PAID } },
    include: { lines: true, payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } } },
  });
  const duesBalance = open.reduce((n, i) => n + Math.max(0, i.amount - i.payments.reduce((m, p) => m + p.amount, 0)), 0);
  // Final-month pro-rata: the unused days of the rent cycle the last day falls in.
  let prorataCredit = 0;
  if (s.property?.prorataEnabled) {
    const day = dayOnly(lastDay);
    const current = open.find((i) => i.type === InvoiceType.RENT && !i.lines.some((l) => l.kind === InvoiceLineKind.PRORATA_CREDIT) && (() => { const span = cycleSpan(i.periodMonth, i.cycleMonths); return day >= span.start && day < span.end; })());
    if (current) {
      const span = cycleSpan(current.periodMonth, current.cycleMonths);
      const from = current.coveredFrom ? utcDay(current.coveredFrom) : span.start;
      const totalDays = Math.round((span.end.getTime() - from.getTime()) / DAY_MS) + 1;
      const unusedDays = Math.round((span.end.getTime() - day.getTime()) / DAY_MS);
      const rent = current.lines.find((l) => l.kind === InvoiceLineKind.RENT)?.amount ?? current.amount;
      const balance = current.amount - current.payments.reduce((m, p) => m + p.amount, 0);
      prorataCredit = Math.min(Math.round((rent * unusedDays) / totalDays), Math.max(0, balance));
    }
  }
  const refundDays = s.property?.refundDays ?? 15;
  return { depositHeld, duesBalance, prorataCredit, netDues: Math.max(0, duesBalance - prorataCredit), promisedDate: new Date(dayOnly(lastDay).getTime() + refundDays * DAY_MS), noticeDays: s.property?.noticeDays ?? 30, refundDays };
}

export function computeRefund(p: { depositHeld: number; duesBalance: number; prorataCredit: number }, deductions: Deduction[]) {
  const deductionsTotal = deductions.reduce((n, d) => n + Math.max(0, Math.floor(d.amount)), 0);
  const netDues = Math.max(0, p.duesBalance - p.prorataCredit);
  const owed = deductionsTotal + netDues;
  return { deductionsTotal, netDues, refundDue: Math.max(0, p.depositHeld - owed), shortfall: Math.max(0, owed - p.depositHeld) };
}

async function activeMoveOut(studentProfileId: string) {
  return db.moveOut.findFirst({ where: { studentProfileId, status: { notIn: [MoveOutStatus.REFUNDED, MoveOutStatus.CANCELLED] } }, include: moveOutInclude, orderBy: { createdAt: 'desc' } });
}

/**
 * Give notice. A student must respect the property's notice days; the
 * office may set any day from today. One open move-out per student.
 */
export async function startMoveOut(studentProfileId: string, input: { lastDay: Date; reason?: string; by: 'STUDENT' | 'OFFICE'; userId: string }) {
  const tenantId = getTenantIdOrThrow();
  const s = await studentWithRoom(studentProfileId);
  if (!s.bedId) throw new ConflictError('This student has no bed to move out of', 'NO_BED');
  if (await activeMoveOut(studentProfileId)) throw new ConflictError('A move-out is already in progress for this student', 'MOVE_OUT_EXISTS');
  const today = todayUtc();
  const lastDay = dayOnly(input.lastDay);
  if (lastDay.getTime() < today.getTime()) throw new BadRequestError('The last day cannot be in the past');
  const noticeDays = s.property?.noticeDays ?? 30;
  if (input.by === 'STUDENT' && lastDay.getTime() < today.getTime() + noticeDays * DAY_MS) {
    throw new BadRequestError(`${s.property?.name ?? 'The hostel'} asks for ${noticeDays} days’ notice — the earliest last day is ${new Date(today.getTime() + noticeDays * DAY_MS).toISOString().slice(0, 10)}`, 'NOTICE_TOO_SHORT');
  }
  // An office-started move-out is an operational departure, not merely a
  // notice: close/cancel dormitory stays and release the physical bed now.
  // A resident's own future notice keeps their bed until the office acts.
  if (input.by === 'OFFICE') {
    const openStays = await db.stay.findMany({ where: { studentProfileId, status: { in: [StayStatus.BOOKED, StayStatus.CHECKED_IN] } }, select: { id: true, status: true } });
    if (openStays.length > 0) {
      const stays = await import('../stays/stays.service');
      for (const stay of openStays) {
        if (stay.status === StayStatus.CHECKED_IN) await stays.checkOut(stay.id, { at: new Date() });
        else await stays.cancelStay(stay.id);
      }
    }
    // Hostel/PG assignments do not have Stay rows. Release those directly;
    // the settlement applies any pro-rata credit later, exactly once.
    const current = await db.studentProfile.findFirst({ where: { id: studentProfileId }, select: { bedId: true } });
    if (current?.bedId) {
      await db.$transaction(async (tx) => {
        await tx.bed.update({ where: { id: current.bedId! }, data: { status: BedStatus.VACANT } });
        await tx.room.updateMany({ where: { billedStudentProfileId: studentProfileId }, data: { billedStudentProfileId: null } });
        await tx.studentProfile.update({ where: { id: studentProfileId }, data: { bedId: null, vacatedAt: new Date() } });
      });
    }
  }
  const row = await db.moveOut.create({
    data: { tenantId, studentProfileId, propertyId: s.propertyId ?? s.bed!.room.propertyId, lastDay, startedBy: input.by, startedById: input.userId, reason: input.reason?.slice(0, 300) ?? null },
    include: moveOutInclude,
  });
  await db.studentProfile.update({ where: { id: studentProfileId }, data: { residencyStatus: 'NOTICE' } });
  const refreshed = input.by === 'OFFICE' ? await db.moveOut.findFirstOrThrow({ where: { id: row.id }, include: moveOutInclude }) : row;
  return { moveOut: publicMoveOut(refreshed), preview: await settlementPreview(studentProfileId, lastDay) };
}

export async function listMoveOuts(propertyId?: string, status?: MoveOutStatus) {
  const rows = await db.moveOut.findMany({
    where: { ...(propertyId ? { propertyId } : {}), ...(status ? { status } : { status: { not: MoveOutStatus.CANCELLED } }) },
    include: moveOutInclude,
    orderBy: [{ lastDay: 'asc' }],
    take: 300,
  });
  const items = rows.map(publicMoveOut);
  const refundsOverdue = items.filter((m) => m.settlement?.overdue && m.status !== MoveOutStatus.REFUNDED).length;
  return { items, refundsOverdue };
}

/**
 * The board a page at a time (Sprint L3): one column's statuses (or all but
 * cancelled), soonest last day first as before. `refundsOverdue` and `counts`
 * (per status) cover the whole property, not the page, so the header badge
 * and the column totals stay right while each column loads as it is scrolled.
 */
export async function pageMoveOuts(propertyId: string | undefined, statuses: MoveOutStatus[] | undefined, pagination: Pagination) {
  const scope: Prisma.MoveOutWhereInput = { ...(propertyId ? { propertyId } : {}), status: { not: MoveOutStatus.CANCELLED } };
  const where: Prisma.MoveOutWhereInput = { ...scope, ...(statuses?.length ? { status: { in: statuses } } : {}) };
  const [rows, total, refundsOverdue, grouped] = await Promise.all([
    db.moveOut.findMany({ where, include: moveOutInclude, orderBy: [{ lastDay: 'asc' }, { id: 'asc' }], skip: pagination.skip, take: pagination.limit }),
    db.moveOut.count({ where }),
    db.moveOut.count({ where: { ...scope, status: { notIn: [MoveOutStatus.CANCELLED, MoveOutStatus.REFUNDED] }, settlement: { refundedAt: null, promisedDate: { lt: todayUtc() } } } }),
    db.moveOut.groupBy({ by: ['status'], where: scope, _count: { _all: true } }),
  ]);
  const counts = Object.fromEntries(grouped.map((g) => [g.status, g._count._all]));
  return { ...paginated(rows.map(publicMoveOut), total, pagination), refundsOverdue, counts };
}

export async function getMoveOut(id: string) {
  const row = await db.moveOut.findFirst({ where: { id }, include: moveOutInclude });
  if (!row) throw new NotFoundError('Move-out not found');
  const [preview, checks] = await Promise.all([settlementPreview(row.studentProfileId, row.lastDay), listAssetChecks(row.studentProfileId)]);
  return { moveOut: publicMoveOut(row), preview, checks, proposedDeductions: checks.out ? proposeDeductions(checks.in?.items ?? null, checks.out.items) : [] };
}

export async function updateMoveOut(id: string, input: { lastDay?: Date; reason?: string | null }) {
  const row = await db.moveOut.findFirst({ where: { id }, include: moveOutInclude });
  if (!row) throw new NotFoundError('Move-out not found');
  if (row.status === MoveOutStatus.REFUNDED || row.status === MoveOutStatus.CANCELLED) throw new ConflictError('This move-out is closed');
  if (row.status === MoveOutStatus.SHARED && input.lastDay) throw new ConflictError('The settlement has been shared; cancel it to change the last day');
  const updated = await db.moveOut.update({ where: { id }, data: { ...(input.lastDay ? { lastDay: dayOnly(input.lastDay) } : {}), ...(input.reason !== undefined ? { reason: input.reason } : {}) }, include: moveOutInclude });
  return publicMoveOut(updated);
}

export async function cancelMoveOut(id: string) {
  const row = await db.moveOut.findFirst({ where: { id }, include: moveOutInclude });
  if (!row) throw new NotFoundError('Move-out not found');
  if (row.status === MoveOutStatus.REFUNDED) throw new ConflictError('A refunded move-out cannot be cancelled');
  const updated = await db.moveOut.update({ where: { id }, data: { status: MoveOutStatus.CANCELLED, cancelledAt: new Date() }, include: moveOutInclude });
  await db.studentProfile.update({ where: { id: row.studentProfileId }, data: { residencyStatus: 'ACTIVE' } });
  return publicMoveOut(updated);
}

// ── Settlement ─────────────────────────────────────────────────────────────

/** Save (or re-save) the draft: deductions, promised date, notes. Figures recomputed from the books. */
export async function upsertSettlement(moveOutId: string, input: { deductions: Deduction[]; promisedDate?: Date; notes?: string | null }) {
  const tenantId = getTenantIdOrThrow();
  const m = await db.moveOut.findFirst({ where: { id: moveOutId }, include: moveOutInclude });
  if (!m) throw new NotFoundError('Move-out not found');
  if (m.status === MoveOutStatus.REFUNDED || m.status === MoveOutStatus.CANCELLED) throw new ConflictError('This move-out is closed');
  if (m.status === MoveOutStatus.SHARED) throw new ConflictError('The settlement has been shared with the student. Reopen it before editing.', 'SETTLEMENT_SHARED');
  const deductions: Deduction[] = input.deductions.slice(0, 50).map((d) => ({ label: d.label.trim().slice(0, 80), amount: Math.max(0, Math.floor(d.amount)), note: d.note?.slice(0, 300) ?? null, photoKey: d.photoKey?.slice(0, 500) ?? null, fromCheck: !!d.fromCheck })).filter((d) => d.label);
  const preview = await settlementPreview(m.studentProfileId, m.lastDay);
  const calc = computeRefund(preview, deductions);
  const data = {
    tenantId,
    moveOutId,
    depositHeld: preview.depositHeld,
    duesBalance: preview.duesBalance,
    prorataCredit: preview.prorataCredit,
    deductions: deductions as unknown as Prisma.InputJsonValue,
    deductionsTotal: calc.deductionsTotal,
    refundDue: calc.refundDue,
    shortfall: calc.shortfall,
    promisedDate: input.promisedDate ? dayOnly(input.promisedDate) : preview.promisedDate,
    notes: input.notes?.slice(0, 1000) ?? null,
  };
  const s = await db.settlement.upsert({ where: { moveOutId }, create: data, update: data });
  const updated = await db.moveOut.update({ where: { id: moveOutId }, data: { status: MoveOutStatus.DRAFT }, include: moveOutInclude });
  return { ...publicMoveOut(updated), settlement: publicSettlement(s) };
}

/**
 * Share the settlement with the student. From here the figures are fixed:
 * the pro-rata credit is applied to the rent invoice, a shortfall becomes a
 * final invoice, and the document is generated and emailed.
 */
export async function shareSettlement(moveOutId: string) {
  const tenantId = getTenantIdOrThrow();
  const m = await db.moveOut.findFirst({ where: { id: moveOutId }, include: moveOutInclude });
  if (!m) throw new NotFoundError('Move-out not found');
  if (!m.settlement) throw new BadRequestError('Save a settlement draft first');
  if (m.status === MoveOutStatus.SHARED) return publicMoveOut(m);
  if (m.status === MoveOutStatus.REFUNDED || m.status === MoveOutStatus.CANCELLED) throw new ConflictError('This move-out is closed');

  // Recompute at the moment of sharing, so a payment that landed since the draft counts.
  const preview = await settlementPreview(m.studentProfileId, m.lastDay);
  const deductions = m.settlement.deductions as unknown as Deduction[];
  const calc = computeRefund(preview, deductions);

  const shared = await db.$transaction(async (tx) => {
    // 1. The final-month credit, on the books.
    if (preview.prorataCredit > 0) {
      const { applyMoveOutCredit } = await import('../billing/billing-rules.service');
      await applyMoveOutCredit(tx, m.studentProfileId, m.lastDay);
    }
    // 2. A shortfall is a final invoice, never a negative refund.
    let shortfallInvoiceId: string | null = null;
    if (calc.shortfall > 0) {
      const period = dayOnly(m.lastDay).toISOString().slice(0, 7);
      const inv = await tx.invoice.create({
        data: {
          tenantId,
          studentProfileId: m.studentProfileId,
          type: InvoiceType.OTHER,
          periodMonth: period,
          cycleMonths: 1,
          amount: calc.shortfall,
          dueDate: dayOnly(m.lastDay),
          lines: {
            create: [
              ...deductions.map((d) => ({ tenantId, kind: InvoiceLineKind.CHARGE, label: `Move-out deduction · ${d.label}`, amount: d.amount, meta: { settlement: true, note: d.note ?? null } })),
              ...(preview.depositHeld > 0 ? [{ tenantId, kind: InvoiceLineKind.PRORATA_CREDIT, label: `Security deposit adjusted (${preview.depositHeld} held)`, amount: -preview.depositHeld, meta: { settlement: true } }] : []),
              ...(calc.netDues > 0 ? [{ tenantId, kind: InvoiceLineKind.CHARGE, label: 'Unpaid dues carried into settlement', amount: calc.netDues, meta: { settlement: true, carried: true } }] : []),
            ].filter((l) => l.amount !== 0),
          },
        },
        select: { id: true },
      });
      shortfallInvoiceId = inv.id;
    }
    const s = await tx.settlement.update({
      where: { moveOutId },
      data: { depositHeld: preview.depositHeld, duesBalance: preview.duesBalance, prorataCredit: preview.prorataCredit, deductionsTotal: calc.deductionsTotal, refundDue: calc.refundDue, shortfall: calc.shortfall, shortfallInvoiceId, sharedAt: new Date() },
    });
    const updated = await tx.moveOut.update({ where: { id: moveOutId }, data: { status: MoveOutStatus.SHARED }, include: moveOutInclude });
    return { ...updated, settlement: s };
  });
  return publicMoveOut(shared as MoveOutRow);
}

/** Back to draft after a share — a dispute resolved, a typo found. Shortfall invoice is removed if unpaid. */
export async function reopenSettlement(moveOutId: string) {
  const m = await db.moveOut.findFirst({ where: { id: moveOutId }, include: moveOutInclude });
  if (!m?.settlement) throw new NotFoundError('Settlement not found');
  if (m.status !== MoveOutStatus.SHARED && m.status !== MoveOutStatus.DISPUTED) throw new ConflictError('Only a shared settlement can be reopened');
  if (m.settlement.shortfallInvoiceId) {
    const inv = await db.invoice.findFirst({ where: { id: m.settlement.shortfallInvoiceId }, include: { payments: { select: { id: true } } } });
    if (inv && inv.payments.length === 0) await db.invoice.delete({ where: { id: inv.id } });
  }
  await db.settlement.update({ where: { moveOutId }, data: { sharedAt: null, shortfallInvoiceId: null } });
  const updated = await db.moveOut.update({ where: { id: moveOutId }, data: { status: MoveOutStatus.DRAFT }, include: moveOutInclude });
  return publicMoveOut(updated);
}

/**
 * The refund went out. Recorded like a payment (method, reference, date);
 * the deposit ledger closes, the bed frees, and the student becomes
 * Vacated — keeping read access to their receipts.
 */
export async function recordRefund(moveOutId: string, input: { amount?: number; method: string; reference?: string; paidAt?: Date; note?: string }) {
  const m = await db.moveOut.findFirst({ where: { id: moveOutId }, include: moveOutInclude });
  if (!m?.settlement) throw new NotFoundError('Settlement not found');
  if (m.status !== MoveOutStatus.SHARED && m.status !== MoveOutStatus.DISPUTED) throw new ConflictError('Share the settlement with the student before recording the refund', 'NOT_SHARED');
  const amount = input.amount ?? m.settlement.refundDue;
  if (amount < 0 || amount > m.settlement.refundDue) throw new BadRequestError(`The refund must be between ₹0 and ₹${m.settlement.refundDue}`);
  const refundedAt = input.paidAt ?? new Date();

  await db.settlement.update({
    where: { moveOutId },
    data: { refundedAt, refundAmount: amount, refundMethod: input.method, refundReference: input.reference ?? null, notes: input.note ? `${m.settlement.notes ? `${m.settlement.notes}\n` : ''}Refund: ${input.note}` : m.settlement.notes },
  });
  // The deposit ledger: what was returned, and what the hostel kept.
  await db.studentProfile.update({
    where: { id: m.studentProfileId },
    data: { depositRefunded: { increment: m.settlement.depositHeld }, depositRefundedAt: refundedAt, depositNote: `Settled ${refundedAt.toISOString().slice(0, 10)}: ₹${amount} refunded${m.settlement.deductionsTotal ? `, ₹${m.settlement.deductionsTotal} deducted` : ''}${m.settlement.duesBalance ? `, ₹${Math.max(0, m.settlement.duesBalance - m.settlement.prorataCredit)} dues adjusted` : ''}`.slice(0, 300) },
  });
  // Free the bed (the pro-rata credit was applied on share, so none is added here).
  if (m.student.bedId) await vacateBed(m.studentProfileId, m.lastDay);
  await db.studentProfile.update({ where: { id: m.studentProfileId }, data: { residencyStatus: 'VACATED', vacatedAt: m.lastDay } });
  const updated = await db.moveOut.update({ where: { id: moveOutId }, data: { status: MoveOutStatus.REFUNDED }, include: moveOutInclude });
  return publicMoveOut(updated);
}

/**
 * An employee hostel has no settlement (4 Nov 2026): the company pays, so
 * nothing is held, owed or refunded. The office closes the move-out, the bed
 * frees and the employee is marked as vacated. REFUNDED stays the one closed
 * status, so every list and older client reads this as finished.
 */
export async function closeMoveOut(moveOutId: string) {
  const m = await db.moveOut.findFirst({ where: { id: moveOutId }, include: moveOutInclude });
  if (!m) throw new NotFoundError('Move-out not found');
  if (m.status === MoveOutStatus.REFUNDED || m.status === MoveOutStatus.CANCELLED) throw new ConflictError('This move-out is closed');
  // Closed ahead of the planned day: they left today, and that is what the record should say.
  const today = todayUtc();
  const lastDay = dayOnly(m.lastDay).getTime() > today.getTime() ? today : dayOnly(m.lastDay);
  if (m.student.bedId) await vacateBed(m.studentProfileId, lastDay);
  await db.studentProfile.update({ where: { id: m.studentProfileId }, data: { residencyStatus: 'VACATED', vacatedAt: lastDay } });
  const updated = await db.moveOut.update({ where: { id: moveOutId }, data: { status: MoveOutStatus.REFUNDED, lastDay }, include: moveOutInclude });
  return publicMoveOut(updated);
}

// ── Student side ───────────────────────────────────────────────────────────

export async function myMoveOut(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true, propertyId: true, residencyStatus: true, property: { select: { noticeDays: true, refundDays: true } } } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  const row = await db.moveOut.findFirst({ where: { studentProfileId: profile.id, status: { not: MoveOutStatus.CANCELLED } }, include: moveOutInclude, orderBy: { createdAt: 'desc' } });
  const today = todayUtc();
  // A draft is the office's working copy; the student sees figures only once shared.
  const mine = row ? publicMoveOut(row) : null;
  if (mine && mine.settlement && !mine.settlement.sharedAt) mine.settlement = null;
  return {
    residencyStatus: profile.residencyStatus,
    policy: { noticeDays: profile.property?.noticeDays ?? 30, refundDays: profile.property?.refundDays ?? 15, earliestLastDay: new Date(today.getTime() + (profile.property?.noticeDays ?? 30) * DAY_MS) },
    moveOut: mine,
  };
}

export async function myStartMoveOut(userId: string, input: { lastDay: Date; reason?: string }) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  return startMoveOut(profile.id, { ...input, by: 'STUDENT', userId });
}

export async function myCancelMoveOut(userId: string) {
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  const row = await db.moveOut.findFirst({ where: { studentProfileId: profile.id, status: MoveOutStatus.NOTICE } });
  if (!row) throw new ConflictError('Only a notice that the office has not started working on can be withdrawn');
  return cancelMoveOut(row.id);
}

/** "Dispute settlement": a request thread with the warden, linked to the settlement. */
export async function disputeSettlement(userId: string, body: string) {
  const tenantId = getTenantIdOrThrow();
  const profile = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!profile) throw new NotFoundError('No student profile for this account');
  const m = await db.moveOut.findFirst({ where: { studentProfileId: profile.id, status: { in: [MoveOutStatus.SHARED, MoveOutStatus.DISPUTED] } }, include: moveOutInclude, orderBy: { createdAt: 'desc' } });
  if (!m?.settlement) throw new ConflictError('There is no shared settlement to dispute');
  if (m.settlement.disputeRequestId) throw new ConflictError('A dispute is already open on this settlement');
  const request = await db.studentRequest.create({
    data: { tenantId, studentProfileId: profile.id, type: StudentRequestType.DISPUTE_SETTLEMENT, subject: `Settlement dispute · refund of ₹${m.settlement.refundDue}`, body: body.slice(0, 2000) },
  });
  await db.settlement.update({ where: { moveOutId: m.id }, data: { disputeRequestId: request.id } });
  const updated = await db.moveOut.update({ where: { id: m.id }, data: { status: MoveOutStatus.DISPUTED }, include: moveOutInclude });
  return { moveOut: publicMoveOut(updated), requestId: request.id };
}
