import { BedStatus, Role } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { ConflictError, NotFoundError } from '../../lib/errors';
import { inBackground, pushTo, staffWith } from '../notifications/notifications.service';

/**
 * Employees with special needs (Sprint 6, TEPL): what each needs (mobility,
 * vision, hearing, medical), which rooms and beds suit them, a check before
 * a bed is given, priority on their requests, help when they ask for it, and
 * a flag on the emergency headcount for those who need help getting out.
 * Not medical detail — that stays in the OHC's record.
 */

export const CATEGORIES = ['MOBILITY', 'VISION', 'HEARING', 'MEDICAL', 'OTHER'] as const;
export const ROOM_FEATURES = ['WHEELCHAIR', 'GROUND_FLOOR', 'GRAB_RAILS', 'VISUAL_ALARM', 'NEAR_EXIT'] as const;
export const ASSISTANCE_KINDS = ['ESCORT', 'ROOM_HELP', 'CLINIC_COMPANION', 'EVACUATION_BUDDY', 'OTHER'] as const;

export interface ProfileInput {
  categories: string[];
  needs?: string | null;
  needsAccessibleRoom?: boolean;
  evacuationHelp?: boolean;
}

/** Does this bed suit this person? Reasons when it does not. */
export function fit(p: { categories: string[]; needsAccessibleRoom: boolean }, bed: { accessible: boolean; room: { floor: number | null; accessibleFeatures: string[] } }) {
  const reasons: string[] = [];
  const f = bed.room.accessibleFeatures;
  if (p.needsAccessibleRoom && !bed.accessible && !f.includes('WHEELCHAIR') && !f.includes('GROUND_FLOOR')) reasons.push('Needs an accessible room or bed: this is neither ground floor, wheelchair-ready nor an accessible bed');
  if (p.categories.includes('HEARING') && !f.includes('VISUAL_ALARM')) reasons.push('No visual fire alarm in this room');
  if (p.categories.includes('VISION') && !f.includes('NEAR_EXIT') && (bed.room.floor ?? 0) > 1) reasons.push('Upstairs and not near an exit');
  return { fits: reasons.length === 0, reasons };
}

const bedSelect = { id: true, label: true, accessible: true, status: true, room: { select: { id: true, number: true, floor: true, accessibleFeatures: true, propertyId: true } } } as const;

// ── Profiles ────────────────────────────────────────────────────────────────

/** Everyone with a profile, where they sleep, and whether it suits them. */
export async function listProfiles(propertyId?: string) {
  const rows = await db.accessibilityProfile.findMany({ take: 2000 });
  const people = await db.studentProfile.findMany({
    where: { id: { in: rows.map((r) => r.studentProfileId) }, residencyStatus: { not: 'VACATED' }, ...(propertyId ? { propertyId } : {}) },
    select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: bedSelect } },
  });
  return people.map((p) => {
    const prof = rows.find((r) => r.studentProfileId === p.id)!;
    const check = p.bed ? fit(prof, p.bed) : { fits: false, reasons: ['No bed yet'] };
    return { ...prof, name: p.user.name, phone: p.user.phone, employeeCode: p.employeeCode, room: p.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null, floor: p.bed?.room.floor ?? null, ...check };
  });
}

export async function saveProfile(studentProfileId: string, input: ProfileInput, actorId: string) {
  if (!(await db.studentProfile.findFirst({ where: { id: studentProfileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
  const data = { categories: [...new Set(input.categories)], needs: input.needs ?? null, needsAccessibleRoom: !!input.needsAccessibleRoom, evacuationHelp: !!input.evacuationHelp, updatedById: actorId };
  if (!data.categories.length) {
    await db.accessibilityProfile.deleteMany({ where: { studentProfileId } });
    return null;
  }
  return db.accessibilityProfile.upsert({ where: { studentProfileId }, create: { tenantId: getTenantIdOrThrow(), studentProfileId, ...data }, update: data });
}

async function myProfileId(userId: string) {
  const p = await db.studentProfile.findFirst({ where: { userId }, select: { id: true } });
  if (!p) throw new NotFoundError('No employee record for this account');
  return p.id;
}

export async function myProfile(userId: string) {
  return db.accessibilityProfile.findFirst({ where: { studentProfileId: await myProfileId(userId) } });
}

export async function saveMyProfile(userId: string, input: ProfileInput) {
  return saveProfile(await myProfileId(userId), input, userId);
}

// ── Rooms and beds ──────────────────────────────────────────────────────────

/** Rooms with what makes them accessible, their accessible beds, and how many of those are free. */
export async function rooms(propertyId?: string) {
  const list = await db.room.findMany({ where: { archivedAt: null, ...(propertyId ? { propertyId } : {}) }, select: { id: true, number: true, floor: true, propertyId: true, accessibleFeatures: true, beds: { where: { archivedAt: null }, select: { id: true, label: true, accessible: true, status: true } } }, orderBy: [{ floor: 'asc' }, { number: 'asc' }], take: 3000 });
  return list.map((r) => ({ ...r, accessibleBeds: r.beds.filter((b) => b.accessible).length, freeAccessible: r.beds.filter((b) => (b.accessible || r.accessibleFeatures.length > 0) && b.status === BedStatus.VACANT).length }));
}

export async function setRoomFeatures(roomId: string, features: string[]) {
  if (!(await db.room.findFirst({ where: { id: roomId }, select: { id: true } }))) throw new NotFoundError('Room not found');
  return db.room.update({ where: { id: roomId }, data: { accessibleFeatures: [...new Set(features)] }, select: { id: true, number: true, accessibleFeatures: true } });
}

export async function setBedAccessible(bedId: string, accessible: boolean) {
  if (!(await db.bed.findFirst({ where: { id: bedId }, select: { id: true } }))) throw new NotFoundError('Bed not found');
  return db.bed.update({ where: { id: bedId }, data: { accessible }, select: { id: true, label: true, accessible: true } });
}

/** Before giving a bed: does it suit them? With no profile, anything does. */
export async function checkBed(studentProfileId: string, bedId: string) {
  const [prof, bed] = await Promise.all([db.accessibilityProfile.findFirst({ where: { studentProfileId } }), db.bed.findFirst({ where: { id: bedId }, select: bedSelect })]);
  if (!bed) throw new NotFoundError('Bed not found');
  return prof ? fit(prof, bed) : { fits: true, reasons: [] };
}

/** Vacant beds that suit someone, best first: ground floor and accessible beds ahead. */
export async function suggestBeds(studentProfileId: string, propertyId?: string) {
  const prof = await db.accessibilityProfile.findFirst({ where: { studentProfileId } });
  const beds = await db.bed.findMany({ where: { status: BedStatus.VACANT, archivedAt: null, room: { archivedAt: null, ...(propertyId ? { propertyId } : {}) } }, select: bedSelect, take: 2000 });
  return beds
    .map((b) => ({ bedId: b.id, label: b.label, roomId: b.room.id, room: b.room.number, floor: b.room.floor, features: b.room.accessibleFeatures, accessible: b.accessible, ...(prof ? fit(prof, b) : { fits: true, reasons: [] }) }))
    .filter((b) => b.fits)
    .sort((a, b) => Number(b.accessible) - Number(a.accessible) || (a.floor ?? 0) - (b.floor ?? 0))
    .slice(0, 30);
}

/** For the requests desk and the headcount: who has a profile, and who needs help to evacuate. */
export async function flagsFor(ids: string[]) {
  const rows = ids.length ? await db.accessibilityProfile.findMany({ where: { studentProfileId: { in: ids } }, select: { studentProfileId: true, categories: true, evacuationHelp: true } }) : [];
  return new Map(rows.map((r) => [r.studentProfileId, r]));
}

// ── Assistance ──────────────────────────────────────────────────────────────

export async function requestAssistance(userId: string, input: { kind: string; note?: string | null; neededAt?: Date | null }) {
  const id = await myProfileId(userId);
  const open = await db.assistanceRequest.count({ where: { studentProfileId: id, status: { in: ['OPEN', 'ACCEPTED'] } } });
  if (open >= 3) throw new ConflictError('You have three requests open already');
  const r = await db.assistanceRequest.create({ data: { tenantId: getTenantIdOrThrow(), studentProfileId: id, kind: input.kind, note: input.note ?? null, neededAt: input.neededAt ?? null } });
  const tenantId = getTenantIdOrThrow();
  inBackground('push: assistance', async () => {
    const staff = await staffWith(tenantId, 'MANAGE_STUDENTS');
    const p = await db.studentProfile.findFirst({ where: { id }, select: { user: { select: { name: true } }, bed: { select: { label: true, room: { select: { number: true } } } } } });
    await pushTo(tenantId, 'ASSISTANCE_REQUEST', r.id, staff, { title: `Help needed: ${p?.user.name ?? 'an employee'}`, body: `${input.kind.replace(/_/g, ' ').toLowerCase()}${p?.bed ? ` · Room ${p.bed.room.number}` : ''}${input.note ? ` — ${input.note}` : ''}`, data: { assistanceId: r.id } });
  });
  return r;
}

export async function myAssistance(userId: string) {
  return db.assistanceRequest.findMany({ where: { studentProfileId: await myProfileId(userId) }, orderBy: { createdAt: 'desc' }, take: 30 });
}

export async function cancelMyAssistance(userId: string, id: string) {
  const r = await db.assistanceRequest.findFirst({ where: { id, studentProfileId: await myProfileId(userId) } });
  if (!r) throw new NotFoundError('Request not found');
  if (r.status !== 'OPEN' && r.status !== 'ACCEPTED') throw new ConflictError('This request is closed');
  return db.assistanceRequest.update({ where: { id }, data: { status: 'CANCELLED' } });
}

export async function listAssistance(status?: string, propertyId?: string) {
  const rows = await db.assistanceRequest.findMany({ where: { ...(status ? { status } : { status: { in: ['OPEN', 'ACCEPTED'] } }) }, orderBy: [{ neededAt: 'asc' }, { createdAt: 'asc' }], take: 300 });
  const people = await db.studentProfile.findMany({ where: { id: { in: rows.map((r) => r.studentProfileId) }, ...(propertyId ? { propertyId } : {}) }, select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true } } } } } });
  const who = new Map(people.map((p) => [p.id, p]));
  const staff = new Map((await db.user.findMany({ where: { id: { in: rows.map((r) => r.assigneeId).filter((x): x is string => !!x) } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  return rows
    .filter((r) => who.has(r.studentProfileId))
    .map((r) => {
      const p = who.get(r.studentProfileId)!;
      return { ...r, name: p.user.name, phone: p.user.phone, employeeCode: p.employeeCode, room: p.bed ? `Room ${p.bed.room.number} · Bed ${p.bed.label}` : null, assignee: r.assigneeId ? staff.get(r.assigneeId) ?? null : null };
    });
}

export async function updateAssistance(id: string, input: { status?: string; assigneeId?: string | null }) {
  const r = await db.assistanceRequest.findFirst({ where: { id } });
  if (!r) throw new NotFoundError('Request not found');
  if (r.status === 'DONE' || r.status === 'CANCELLED') throw new ConflictError('This request is closed');
  if (input.status === 'OPEN' && r.status !== 'ACCEPTED') throw new ConflictError('Only an accepted request can be put back');
  if (input.assigneeId && !(await db.user.findFirst({ where: { id: input.assigneeId, role: { not: Role.STUDENT } }, select: { id: true } }))) throw new NotFoundError('Staff member not found');
  return db.assistanceRequest.update({ where: { id }, data: { ...input, ...(input.status === 'OPEN' ? { assigneeId: null } : {}), ...(input.status === 'DONE' ? { doneAt: new Date() } : {}) } });
}
