import { BedStatus, Prisma, StayStatus, TenantKind } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { nextBedLabels, resequencedBedLabels, sortBeds } from '../../lib/bed-labels';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import type { CreateRoomInput, UpdateRoomInput } from './rooms.schemas';
import { assertWithinPlanLimit } from '../plans/plan-limits';
import { paginated, type Pagination } from '../../lib/pagination';

// All queries below use the SCOPED `db` client — tenantId is injected
// automatically, so a Warden/Admin can only ever touch their own tenant's data.

/**
 * The floor a room is on when nobody said: from its number (101 → 1, 1205 →
 * 12), else the ground floor. Beds can only be assigned on a room with a floor
 * (since 28 Oct 2026), so rooms the platform makes by itself (a trial's
 * starter rooms, a sheet import's new rooms) get one; the owner can change it.
 */
export function floorFromRoomNumber(number: string): number {
  const digits = number.trim();
  return /^\d{3,4}$/.test(digits) ? Math.min(200, Math.floor(Number(digits) / 100)) : 0;
}

export async function createRoom(input: CreateRoomInput) {
  // The plan caps beds, so a room is checked for the beds it brings with it.
  await assertWithinPlanLimit('beds', input.bedCount ?? 0);
  const tenantId = getTenantIdOrThrow();
  const property = await db.property.findFirst({ where: { id: input.propertyId } });
  if (!property) throw new NotFoundError('Property not found');

  // A room number should be unique within its property — "101" twice is always
  // a mistake, and it makes every later reference ambiguous.
  const clash = await db.room.findFirst({ where: { propertyId: input.propertyId, number: input.number, archivedAt: null } });
  if (clash) throw new ConflictError(`Room ${input.number} already exists in this property`);

  const room = await db.room.create({
    data: {
      tenantId,
      propertyId: input.propertyId,
      number: input.number,
      floor: input.floor,
      type: input.type,
      notes: input.notes,
      monthlyRent: input.monthlyRent,
      rentDueDay: input.rentDueDay,
      feeCycleMonths: input.feeCycleMonths ?? 1,
      rateBasis: input.rateBasis ?? 'MONTHLY',
      nightlyRent: input.nightlyRent,
    },
  });

  if (input.bedCount && input.bedCount > 0) {
    for (let i = 0; i < input.bedCount; i++) {
      // A, B, C, … by default; 1, 2, 3, … when asked (and past Z).
      const label = input.bedNaming === 'NUMBERS' || i >= 26 ? String(i + 1) : String.fromCharCode(65 + i);
      // Seeding bed rent here is what lets the builder set pricing at creation
      // rather than making the admin walk every bed afterwards.
      await db.bed.create({
        data: { tenantId, roomId: room.id, label, monthlyRent: input.bedRent, rentDueDay: input.rentDueDay, nightlyRent: input.bedNightlyRent },
      });
    }
  }

  return withSortedBeds(await db.room.findFirst({ where: { id: room.id }, include: { beds: { orderBy: { label: 'asc' }, include: await bedOccupant() }, billedStudent: { include: { user: { select: { name: true } } } } } }));
}

/** Beds in natural order (1, 2 … 9, 10), which the database's text order is not. */
function withSortedBeds<R extends { beds: { label: string }[] } | null>(room: R): R {
  return room ? { ...room, beds: sortBeds(room.beds) } : room;
}

/** The occupant a bed carries, so the room card can name who lives where. */
const BED_OCCUPANT = { student: { select: { id: true, user: { select: { name: true } } } } } as const;
/** An enterprise tenant's bed panel also says how to reach them. Behind MANAGE_ROOMS, on the room routes. */
const BED_OCCUPANT_CONTACT = { student: { select: { id: true, employeeCode: true, user: { select: { name: true, phone: true, email: true, hasLogin: true } } } } } as const;
async function bedOccupant() {
  return ((await tenantHasFeature(getTenantIdOrThrow(), 'employeeRecords')) ? BED_OCCUPANT_CONTACT : BED_OCCUPANT) as typeof BED_OCCUPANT;
}

/**
 * Counts for the rooms stat cards. Computed with COUNT rather than by loading
 * rows, so a page of results never becomes the number on the card.
 */
export async function roomStats(propertyId?: string) {
  const roomWhere = { archivedAt: null, floor: { not: null }, ...(propertyId ? { propertyId } : {}) };
  const bedWhere = { archivedAt: null, room: { floor: { not: null }, ...(propertyId ? { propertyId } : {}) } };
  const [rooms, beds, occupied, vacant] = await Promise.all([
    db.room.count({ where: roomWhere }),
    db.bed.count({ where: bedWhere }),
    db.bed.count({ where: { ...bedWhere, status: BedStatus.OCCUPIED } }),
    db.bed.count({ where: { ...bedWhere, status: BedStatus.VACANT } }),
  ]);
  return { rooms, beds, occupied, vacant };
}

/// Unpaged by default: the builds on phones read every room at once. Since
/// Sprint L2 a client can narrow to one floor (`floor`, or `null` for rooms
/// with none) and ask for a page; `/floors` and `/summary` carry what used to
/// need the whole list.
export async function listRooms(propertyId?: string, q?: string, opts: { floor?: number | null; pagination?: Pagination | null } = {}) {
  // Searching in SQL, not the client: a paginated client holds one page, so
  // filtering there would search the page rather than the table.
  const where = {
    archivedAt: null,
    ...(propertyId ? { propertyId } : {}),
    ...(opts.floor !== undefined ? { floor: opts.floor } : {}),
    ...(q
      ? {
          OR: [
            { number: { contains: q, mode: 'insensitive' as const } },
            { type: { contains: q, mode: 'insensitive' as const } },
          ],
        }
      : {}),
  };
  const include = {
    beds: { where: { archivedAt: null }, orderBy: { label: 'asc' as const }, include: await bedOccupant() },
    billedStudent: { include: { user: { select: { name: true } } } },
  };
  const orderBy = [{ floor: 'asc' as const }, { number: 'asc' as const }];

  const pagination = opts.pagination;
  if (!pagination) return (await db.room.findMany({ where, include, orderBy })).map(withSortedBeds);
  const [rows, total] = await Promise.all([
    // The id breaks ties so a room never shows on two pages.
    db.room.findMany({ where, include, orderBy: [...orderBy, { id: 'asc' as const }], skip: pagination.skip, take: pagination.limit }),
    db.room.count({ where }),
  ]);
  return paginated(rows.map(withSortedBeds), total, pagination);
}

/**
 * Beds to pick from, a page at a time (Sprint L4): the bed pickers on the
 * phone read every room to find them, and one read only the rooms already
 * loaded. Vacant beds by default (`any` for every bed, as the stay editor
 * lists); placed rooms only (a floor set), as the web's picker; not archived.
 * `q` matches the room number or the bed's label; `id` picks one bed, of any
 * status. Room order, then the bed.
 */
export async function bedChoices(propertyId: string | undefined, f: { q?: string; any?: boolean; id?: string }, pagination: Pagination) {
  const where: Prisma.BedWhereInput = {
    archivedAt: null,
    // `id` reads one bed whatever its status: the one a form opened with.
    ...(f.id ? { id: f.id } : f.any ? {} : { status: BedStatus.VACANT }),
    room: { archivedAt: null, floor: { not: null }, ...(propertyId ? { propertyId } : {}) },
    ...(f.q ? { OR: [{ room: { number: { contains: f.q, mode: 'insensitive' } } }, { label: { contains: f.q, mode: 'insensitive' } }] } : {}),
  };
  const [rows, total] = await Promise.all([
    db.bed.findMany({
      where,
      select: { id: true, label: true, status: true, accessible: true, isExtra: true, monthlyRent: true, nightlyRent: true, room: { select: { id: true, number: true, floor: true, type: true, propertyId: true, monthlyRent: true, nightlyRent: true } } },
      orderBy: [{ room: { floor: 'asc' } }, { room: { number: 'asc' } }, { label: 'asc' }, { id: 'asc' }],
      skip: pagination.skip,
      take: pagination.limit,
    }),
    db.bed.count({ where }),
  ]);
  return paginated(rows, total, pagination);
}

/** What the getting-started steps ask of the rooms (Sprint L4): beds made, and beds with a rent. */
export async function setupCounts(propertyId?: string) {
  const where = { archivedAt: null, room: { archivedAt: null, ...(propertyId ? { propertyId } : {}) } };
  const [beds, pricedBeds] = await Promise.all([db.bed.count({ where }), db.bed.count({ where: { ...where, monthlyRent: { gt: 0 } } })]);
  return { beds, pricedBeds };
}

/**
 * The property's floors with their counts, and every room number (Sprint L2):
 * enough for a floor picker, the stat cards and the room builder's duplicate
 * check, without downloading the rooms. Counted like `roomStats`: rooms and
 * beds that are not archived.
 */
export async function roomFloors(propertyId?: string) {
  const roomWhere = { archivedAt: null, ...(propertyId ? { propertyId } : {}) };
  const [rooms, beds] = await Promise.all([
    db.room.findMany({ where: roomWhere, select: { id: true, number: true, floor: true }, orderBy: [{ floor: 'asc' }, { number: 'asc' }] }),
    db.bed.groupBy({ by: ['roomId', 'status'], where: { archivedAt: null, room: roomWhere }, _count: { _all: true } }),
  ]);
  const floorOf = new Map(rooms.map((r) => [r.id, r.floor]));
  const floors = new Map<number | null, { floor: number | null; rooms: number; beds: number; occupied: number; vacant: number; reserved: number }>();
  const row = (floor: number | null) => {
    let f = floors.get(floor);
    if (!f) floors.set(floor, (f = { floor, rooms: 0, beds: 0, occupied: 0, vacant: 0, reserved: 0 }));
    return f;
  };
  for (const r of rooms) row(r.floor).rooms++;
  for (const g of beds) {
    const f = row(floorOf.get(g.roomId) ?? null);
    const n = g._count._all;
    f.beds += n;
    if (g.status === BedStatus.OCCUPIED) f.occupied += n;
    else if (g.status === BedStatus.VACANT) f.vacant += n;
    else if (g.status === BedStatus.RESERVED) f.reserved += n;
  }
  return {
    // Floors in order, the rooms with no floor last.
    floors: [...floors.values()].sort((a, b) => (a.floor === null ? 1 : b.floor === null ? -1 : a.floor - b.floor)),
    numbers: rooms.map((r) => r.number),
    /** Rooms without a floor: incomplete inventory, left out of the counts on screen. */
    unflooredRoomIds: rooms.filter((r) => r.floor === null).map((r) => r.id),
  };
}

/**
 * What the dashboards read from rooms (Sprint L2), worked out here instead of
 * on a phone holding every room: the rent the empty beds would bring in, and
 * the occupied rooms nobody is billed for under room pricing. Same rules as
 * the web's `revenueAtRisk` and the mobile `vacantRent`: under ROOM pricing a
 * room counts when it has beds and none is occupied; a dormitory counts each
 * vacant bed's nightly rate; otherwise each vacant bed's monthly rent. Rooms
 * without a floor are left out of the rent, as on screen. A tenant that bills
 * nobody (Enterprise) gets zeros.
 */
export async function roomSummary(propertyId?: string) {
  const tenantId = getTenantIdOrThrow();
  const [billing, tenant, property] = await Promise.all([
    tenantHasFeature(tenantId, 'billing'),
    prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { kind: true } }),
    propertyId ? db.property.findFirst({ where: { id: propertyId }, select: { pricingMode: true } }) : null,
  ]);
  const roomPriced = property?.pricingMode === 'ROOM';
  const nightly = !roomPriced && tenant?.kind === TenantKind.DORMITORY;
  const basis: 'MONTH' | 'NIGHT' = nightly ? 'NIGHT' : 'MONTH';
  if (!billing) return { vacantRent: 0, basis, roomPriced, unbilledRooms: 0 };
  const rooms = await db.room.findMany({
    where: { archivedAt: null, ...(propertyId ? { propertyId } : {}) },
    select: { floor: true, monthlyRent: true, nightlyRent: true, billedStudentProfileId: true, beds: { where: { archivedAt: null }, select: { status: true, monthlyRent: true, nightlyRent: true } } },
  });
  let vacantRent = 0;
  for (const r of rooms) {
    if (r.floor === null) continue;
    if (roomPriced) {
      if (r.beds.length > 0 && r.beds.every((b) => b.status !== BedStatus.OCCUPIED)) vacantRent += r.monthlyRent ?? 0;
    } else {
      for (const b of r.beds) if (b.status === BedStatus.VACANT) vacantRent += nightly ? b.nightlyRent ?? r.nightlyRent ?? 0 : b.monthlyRent ?? 0;
    }
  }
  const unbilledRooms = roomPriced ? rooms.filter((r) => !r.billedStudentProfileId && r.beds.some((b) => b.status === BedStatus.OCCUPIED)).length : 0;
  return { vacantRent, basis, roomPriced, unbilledRooms };
}

export async function updateRoom(id: string, data: UpdateRoomInput) {
  const existing = await db.room.findFirst({ where: { id, archivedAt: null }, include: { beds: { where: { archivedAt: null } } } });
  if (!existing) throw new NotFoundError('Room not found');

  if (data.number && data.number !== existing.number) {
    const clash = await db.room.findFirst({
      where: { propertyId: existing.propertyId, number: data.number, id: { not: id }, archivedAt: null },
    });
    if (clash) throw new ConflictError(`Room ${data.number} already exists in this property`);
  }

  // The student billed for a room must actually occupy it, otherwise the
  // invoice would go to someone who doesn't live there.
  if (data.billedStudentProfileId) {
    const occupant = await db.studentProfile.findFirst({
      where: { id: data.billedStudentProfileId, bedId: { in: existing.beds.map((b) => b.id) } },
    });
    if (!occupant) throw new BadRequestError('That student does not occupy this room');
  }

  return withSortedBeds(
    await db.room.update({
      where: { id },
      data,
      include: {
        beds: { where: { archivedAt: null }, orderBy: { label: 'asc' }, include: await bedOccupant() },
        billedStudent: { include: { user: { select: { name: true } } } },
      },
    }),
  );
}

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

/**
 * Why these beds cannot be taken out of use right now, or null: someone is
 * in one, one is held, or a booking is still to come or under way. Each
 * reason names what to do first.
 */
async function removalBlocker(bedIds: string[]): Promise<string | null> {
  if (bedIds.length === 0) return null;
  const occupant = await db.studentProfile.findFirst({ where: { bedId: { in: bedIds } }, select: { user: { select: { name: true } }, bed: { select: { label: true } } } });
  if (occupant) return `Bed ${occupant.bed?.label ?? ''} is occupied by ${occupant.user.name}. Check them out or move them first.`;
  const busy = await db.bed.findFirst({ where: { id: { in: bedIds }, status: { not: BedStatus.VACANT } }, select: { label: true, status: true } });
  if (busy) return busy.status === BedStatus.OCCUPIED ? `Bed ${busy.label} is occupied. Free it first.` : `Bed ${busy.label} is held. Release the hold first.`;
  const open = { bedId: { in: bedIds }, status: { in: [StayStatus.BOOKED, StayStatus.CHECKED_IN] } };
  const count = await db.stay.count({ where: open });
  if (count === 0) return null;
  const next = await db.stay.findFirst({ where: open, orderBy: { plannedCheckIn: 'asc' }, select: { plannedCheckIn: true, student: { select: { user: { select: { name: true } } } } } });
  return `${count === 1 ? 'A booking is' : `${count} bookings are`} still on ${bedIds.length === 1 ? 'this bed' : 'this room'}${next ? ` (next: ${next.student.user.name}, ${fmtWhen(next.plannedCheckIn)})` : ''}. Cancel or move ${count === 1 ? 'it' : 'them'} first.`;
}

/**
 * Take a room out of use. One that was never booked is deleted outright;
 * one with booking history is archived instead, so past stays and their
 * invoices keep the room and bed they were for. Either way it is gone from
 * the bed map, counts, availability and plan limits.
 */
export async function deleteRoom(id: string): Promise<'deleted' | 'archived'> {
  const room = await db.room.findFirst({ where: { id, archivedAt: null }, include: { beds: { where: { archivedAt: null }, select: { id: true } } } });
  if (!room) throw new NotFoundError('Room not found');
  const why = await removalBlocker(room.beds.map((b) => b.id));
  if (why) throw new ConflictError(why);
  const history = await db.stay.count({ where: { bed: { roomId: id } } });
  if (history === 0) {
    await db.bed.deleteMany({ where: { roomId: id } });
    await db.room.delete({ where: { id } });
    return 'deleted';
  }
  const now = new Date();
  await db.bed.updateMany({ where: { roomId: id, archivedAt: null }, data: { archivedAt: now } });
  await db.room.update({ where: { id }, data: { archivedAt: now, billedStudentProfileId: null } });
  return 'archived';
}

// ── Beds ──────────────────────────────────────────────────────────────────

/**
 * Add beds to a room. With no label the room's next names are used (1, 2, 3
 * … continuing its numbers, else A, B, C); `count` adds several at once and
 * `extra` marks them as extra beds (27 Oct 2026). Returns the first bed, as
 * before, and all of them.
 */
export async function addBeds(roomId: string, opts: { label?: string; count?: number; extra?: boolean } = {}) {
  const tenantId = getTenantIdOrThrow();
  const room = await db.room.findFirst({ where: { id: roomId, archivedAt: null } });
  if (!room) throw new NotFoundError('Room not found');
  const count = opts.label ? 1 : Math.max(1, opts.count ?? 1);
  await assertWithinPlanLimit('beds', count);
  const existing = await db.bed.findMany({ where: { roomId, archivedAt: null }, select: { label: true, monthlyRent: true, rentDueDay: true, nightlyRent: true } });
  let labels: string[];
  if (opts.label) {
    if (existing.some((b) => b.label.toLowerCase() === opts.label!.toLowerCase())) throw new ConflictError(`This room already has a bed called ${opts.label}`);
    labels = [opts.label];
  } else {
    const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { kind: true } });
    labels = nextBedLabels(existing.map((b) => b.label), count, tenant?.kind === TenantKind.DORMITORY);
  }
  // A new bed charges what its roommates charge: one added with no rate
  // would bill nothing until someone noticed. The first bed in natural order.
  const sibling = sortBeds(existing)[0];
  const beds = [];
  for (const label of labels) {
    beds.push(
      await db.bed.create({ data: { tenantId, roomId, label, isExtra: !!opts.extra, monthlyRent: sibling?.monthlyRent, rentDueDay: sibling?.rentDueDay, nightlyRent: sibling?.nightlyRent } }),
    );
  }
  return beds;
}

export async function addBed(roomId: string, label: string) {
  return (await addBeds(roomId, { label }))[0];
}

export async function updateBedStatus(id: string, status: BedStatus) {
  const bed = await db.bed.findFirst({ where: { id, archivedAt: null } });
  if (!bed) throw new NotFoundError('Bed not found');
  if (bed.status === BedStatus.OCCUPIED) {
    throw new BadRequestError('Bed is occupied; unassign the student first');
  }
  return db.bed.update({ where: { id }, data: { status } });
}

/**
 * Rename a bed. Names are unique within a room (ignoring case), so the desk
 * never has two "A"s to choose between. The name is only a label: stays,
 * invoices and the occupant follow the bed, not its name.
 */
export async function renameBed(id: string, label: string) {
  const bed = await db.bed.findFirst({ where: { id, archivedAt: null }, select: { id: true, roomId: true, label: true } });
  if (!bed) throw new NotFoundError('Bed not found');
  if (bed.label === label) return db.bed.findFirst({ where: { id } });
  const clash = await db.bed.findFirst({ where: { roomId: bed.roomId, archivedAt: null, id: { not: id }, label: { equals: label, mode: 'insensitive' } }, select: { id: true } });
  if (clash) throw new ConflictError(`This room already has a bed called ${label}`);
  return db.bed.update({ where: { id }, data: { label } });
}

/** One bed out of use: deleted if never booked, archived if it has booking history. */
export async function deleteBed(id: string): Promise<'deleted' | 'archived'> {
  const bed = await db.bed.findFirst({ where: { id, archivedAt: null } });
  if (!bed) throw new NotFoundError('Bed not found');
  if (bed.status === BedStatus.OCCUPIED) throw new ConflictError('Cannot delete an occupied bed');
  const why = await removalBlocker([id]);
  if (why) throw new ConflictError(why);
  let result: 'deleted' | 'archived';
  if ((await db.stay.count({ where: { bedId: id } })) === 0) {
    await db.bed.delete({ where: { id } });
    result = 'deleted';
  } else {
    await db.bed.update({ where: { id }, data: { archivedAt: new Date() } });
    result = 'archived';
  }

  // Dormitory bed names are positional. If G leaves A..H, the old H becomes
  // G. Hostel/PG rooms and custom labels keep their names unchanged.
  const tenant = await prismaUnscoped.tenant.findUnique({ where: { id: bed.tenantId }, select: { kind: true } });
  if (tenant?.kind === TenantKind.DORMITORY) {
    const remaining = sortBeds(await db.bed.findMany({ where: { roomId: bed.roomId, archivedAt: null }, select: { id: true, label: true } }));
    const labels = resequencedBedLabels(remaining.map((candidate) => candidate.label));
    if (labels) {
      for (let index = 0; index < remaining.length; index++) {
        if (remaining[index].label !== labels[index]) await db.bed.update({ where: { id: remaining[index].id }, data: { label: labels[index] } });
      }
    }
  }
  return result;
}

export async function setBedRent(id: string, monthlyRent: number | null, rentDueDay?: number | null, nightlyRent?: number | null) {
  const bed = await db.bed.findFirst({ where: { id, archivedAt: null } });
  if (!bed) throw new NotFoundError('Bed not found');
  return db.bed.update({
    where: { id },
    data: { monthlyRent, ...(rentDueDay !== undefined ? { rentDueDay } : {}), ...(nightlyRent !== undefined ? { nightlyRent } : {}) },
  });
}
