import { PassStatus, PunchDirection, PunchType, Role, StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { env } from '../../config/env';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { sendSms } from '../../lib/sms';
import { EMERGENCY_PUSH_CHANNEL } from '../../lib/push';
import { inBackground, pushTo } from '../notifications/notifications.service';
import { audienceMembers } from '../communication/audience';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { flagsFor } from '../special-needs/special-needs.service';

/**
 * Emergencies (Sprint 5, TEPL): a fire, a medical emergency, an evacuation —
 * or a drill. Raising one tells every resident of the block and every member
 * of staff at once, by app alert, WhatsApp and SMS. Then the headcount: each
 * resident is accounted for by their own "I'm safe" in the app, a swipe on
 * the roll-call terminal at the assembly point, or a warden marking them;
 * those out of the hostel (on leave, on a pass, or last seen going out) are
 * listed apart. A drill records how long it took and what was seen.
 *
 * The trained emergency team — fire wardens, first aid, marshals — is kept
 * here too, with when each was trained and until when it holds.
 */

export const KINDS = ['FIRE', 'MEDICAL', 'SECURITY', 'WEATHER', 'EVACUATION', 'OTHER'] as const;
export const TEAM_ROLES = ['FIRE_WARDEN', 'FIRST_AID', 'EVACUATION_MARSHAL', 'SECURITY_LEAD', 'OTHER'] as const;

const KIND_WORD: Record<string, string> = { FIRE: 'Fire', MEDICAL: 'Medical emergency', SECURITY: 'Security alert', WEATHER: 'Weather alert', EVACUATION: 'Evacuation', OTHER: 'Emergency' };

// ── Raising and broadcasting ────────────────────────────────────────────────

export async function raiseAlert(input: { kind: string; title: string; message: string; propertyId?: string | null; assemblyPoint?: string | null; isDrill?: boolean }, actorId: string) {
  const tenantId = getTenantIdOrThrow();
  if (input.propertyId && !(await db.property.findFirst({ where: { id: input.propertyId }, select: { id: true } }))) throw new BadRequestError('Unknown block');
  const open = await db.emergencyAlert.findFirst({ where: { closedAt: null, isDrill: !!input.isDrill, ...(input.propertyId ? { OR: [{ propertyId: input.propertyId }, { propertyId: null }] } : {}) }, select: { id: true } });
  if (open) throw new ConflictError(input.isDrill ? 'A drill is already running here — close it first' : 'An alert is already open here — add to it, or close it first');
  const alert = await db.emergencyAlert.create({ data: { tenantId, kind: input.kind, title: input.title, message: input.message, propertyId: input.propertyId ?? null, assemblyPoint: input.assemblyPoint ?? null, isDrill: !!input.isDrill, raisedById: actorId } });
  inBackground('emergency: broadcast', () => broadcast(tenantId, alert.id));
  return alert;
}

/** Everyone at once: residents of the block, all staff, and the emergency team's phones. */
async function broadcast(tenantId: string, alertId: string) {
  const a = await prismaUnscoped.emergencyAlert.findUniqueOrThrow({ where: { id: alertId } });
  const residents = await audienceMembers(tenantId, { propertyId: a.propertyId });
  const staff = await prismaUnscoped.user.findMany({ where: { tenantId, role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN, Role.GUARD] }, deactivatedAt: null }, select: { id: true, phone: true } });
  const team = await prismaUnscoped.emergencyTeamMember.findMany({ where: { tenantId, isActive: true, ...(a.propertyId ? { OR: [{ propertyId: a.propertyId }, { propertyId: null }] } : {}) }, select: { phone: true, userId: true } });
  const prefix = a.isDrill ? 'DRILL — ' : '';
  const headline = `${prefix}${KIND_WORD[a.kind] ?? 'Emergency'}: ${a.title}`;
  const text = `${headline}. ${a.message}${a.assemblyPoint ? ` Go to: ${a.assemblyPoint}.` : ''} Mark yourself safe in the app.`;

  const users = [...new Set([...residents.map((r) => r.userId), ...staff.map((s) => s.id)])];
  await pushTo(tenantId, 'EMERGENCY', alertId, users, { title: headline, body: a.message, data: { alertId, alertKind: a.kind }, channelId: EMERGENCY_PUSH_CHANNEL });

  // One message per phone, whoever it belongs to.
  const phones = new Map<string, string | null>();
  for (const r of residents) if (r.phone) phones.set(r.phone, r.userId);
  for (const s of staff) if (s.phone && !phones.has(s.phone)) phones.set(s.phone, s.id);
  for (const t of team) if (t.phone && !phones.has(t.phone)) phones.set(t.phone, t.userId);
  let whatsapped = 0;
  let texted = 0;
  for (const [phone, userId] of phones) {
    const w = await sendWhatsAppTemplate(phone, env.WHATSAPP_TEMPLATE_EMERGENCY, [headline, a.message], text, { tenantId, userId, purpose: 'BROADCAST' }).catch(() => ({ sent: false, mode: 'error' as const }));
    if (w.sent || w.mode === 'log') whatsapped++;
    const s = await sendSms(phone, text);
    if (s.sent || s.mode === 'log') texted++;
  }
  await prismaUnscoped.emergencyAlert.update({ where: { id: alertId }, data: { pushed: users.length, whatsapped, texted } });
}

// ── The resident ────────────────────────────────────────────────────────────

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

/** Open alerts for my block, with my answer to each. */
export async function myAlerts(userId: string) {
  const p = await profileOf(userId);
  const open = await db.emergencyAlert.findMany({ where: { closedAt: null, OR: [{ propertyId: null }, ...(p.propertyId ? [{ propertyId: p.propertyId }] : [])] }, orderBy: { raisedAt: 'desc' } });
  const acks = await db.emergencyAck.findMany({ where: { studentProfileId: p.id, alertId: { in: open.map((a) => a.id) } } });
  const mine = new Map(acks.map((a) => [a.alertId, a]));
  return open.map((a) => ({ id: a.id, kind: a.kind, title: a.title, message: a.message, assemblyPoint: a.assemblyPoint, isDrill: a.isDrill, raisedAt: a.raisedAt, mine: mine.get(a.id) ? { status: mine.get(a.id)!.status, at: mine.get(a.id)!.at, source: mine.get(a.id)!.source } : null }));
}

export async function answer(userId: string, alertId: string, status: 'SAFE' | 'NEED_HELP', note?: string | null) {
  const p = await profileOf(userId);
  const a = await db.emergencyAlert.findFirst({ where: { id: alertId, closedAt: null, OR: [{ propertyId: null }, ...(p.propertyId ? [{ propertyId: p.propertyId }] : [])] } });
  if (!a) throw new NotFoundError('No open alert');
  return db.emergencyAck.upsert({
    where: { alertId_studentProfileId: { alertId, studentProfileId: p.id } },
    create: { tenantId: getTenantIdOrThrow(), alertId, studentProfileId: p.id, status, source: 'APP', note: note ?? null },
    update: { status, source: 'APP', note: note ?? null, at: new Date() },
  });
}

// ── The headcount ───────────────────────────────────────────────────────────

/**
 * Every resident of the block, sorted into: need help, unaccounted (no word
 * yet and in the hostel as far as we know), safe (by app, roll call or a
 * warden), and away (on leave today, out on a pass, or last seen going out).
 */
export async function headcount(alertId: string) {
  const a = await db.emergencyAlert.findFirst({ where: { id: alertId } });
  if (!a) throw new NotFoundError('Alert not found');
  const tenantId = getTenantIdOrThrow();
  const people = await db.studentProfile.findMany({
    where: { tenantId, residencyStatus: { not: 'VACATED' }, bedId: { not: null }, ...(a.propertyId ? { propertyId: a.propertyId } : {}) },
    select: { id: true, employeeCode: true, user: { select: { name: true, phone: true } }, bed: { select: { label: true, room: { select: { number: true, floor: true } } } }, property: { select: { name: true } } },
    orderBy: [{ bed: { room: { floor: 'asc' } } }, { user: { name: 'asc' } }],
    take: 5000,
  });
  const ids = people.map((p) => p.id);
  const today = new Date(`${new Date(a.raisedAt.getTime() + 330 * 60_000).toISOString().slice(0, 10)}T00:00:00.000Z`);
  const [acks, rollcall, leaves, passes, taps, swipes] = await Promise.all([
    db.emergencyAck.findMany({ where: { alertId } }),
    db.biometricPunch.findMany({ where: { studentProfileId: { in: ids }, type: PunchType.ROLLCALL, punchedAt: { gte: a.raisedAt, ...(a.closedAt ? { lte: a.closedAt } : {}) } }, select: { studentProfileId: true, punchedAt: true }, orderBy: { punchedAt: 'asc' } }),
    db.studentRequest.findMany({ where: { studentProfileId: { in: ids }, type: StudentRequestType.LEAVE, status: StudentRequestStatus.APPROVED, fromDate: { lte: today }, toDate: { gte: today } }, select: { studentProfileId: true } }),
    db.gatePass.findMany({ where: { studentProfileId: { in: ids }, status: { in: [PassStatus.OUT, PassStatus.OVERDUE] } }, select: { studentProfileId: true } }),
    db.gatePunch.findMany({ where: { studentProfileId: { in: ids }, at: { gte: new Date(a.raisedAt.getTime() - 2 * 86_400_000), lte: a.raisedAt } }, select: { studentProfileId: true, direction: true, at: true } }),
    db.biometricPunch.findMany({ where: { studentProfileId: { in: ids }, type: { in: [PunchType.GATE_IN, PunchType.GATE_OUT] }, punchedAt: { gte: new Date(a.raisedAt.getTime() - 2 * 86_400_000), lte: a.raisedAt } }, select: { studentProfileId: true, type: true, punchedAt: true } }),
  ]);
  const ack = new Map(acks.map((x) => [x.studentProfileId, x]));
  const roll = new Map<string, Date>();
  for (const r of rollcall) if (r.studentProfileId && !roll.has(r.studentProfileId)) roll.set(r.studentProfileId, r.punchedAt);
  const lastGate = new Map<string, { dir: 'IN' | 'OUT'; at: Date }>();
  const see = (id: string | null, dir: 'IN' | 'OUT', at: Date) => {
    if (!id) return;
    const cur = lastGate.get(id);
    if (!cur || at > cur.at) lastGate.set(id, { dir, at });
  };
  for (const t of taps) see(t.studentProfileId, t.direction === PunchDirection.OUT ? 'OUT' : 'IN', t.at);
  for (const s of swipes) see(s.studentProfileId, s.type === PunchType.GATE_OUT ? 'OUT' : 'IN', s.punchedAt);
  // Sprint 6 (TEPL): who needs help getting out.
  const needs = (await tenantHasFeature(tenantId, 'specialNeeds')) ? await flagsFor(ids) : new Map<string, { evacuationHelp: boolean; categories: string[] }>();
  const onLeave = new Set(leaves.map((l) => l.studentProfileId));
  const onPass = new Set(passes.map((p) => p.studentProfileId));

  const rows = people.map((p) => {
    const base = { studentProfileId: p.id, 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, block: p.property?.name ?? null, evacuationHelp: !!needs.get(p.id)?.evacuationHelp };
    const k = ack.get(p.id);
    if (k) return { ...base, state: k.status === 'NEED_HELP' ? ('NEED_HELP' as const) : ('SAFE' as const), source: k.source, at: k.at, note: k.note };
    const r = roll.get(p.id);
    if (r) return { ...base, state: 'SAFE' as const, source: 'ROLLCALL', at: r, note: null };
    const away = onLeave.has(p.id) ? 'On leave' : onPass.has(p.id) ? 'Out on a pass' : lastGate.get(p.id)?.dir === 'OUT' ? 'Last seen going out' : null;
    if (away) return { ...base, state: 'AWAY' as const, source: null, at: null, note: away };
    return { ...base, state: 'UNACCOUNTED' as const, source: null, at: null, note: null };
  });
  const count = (s: string) => rows.filter((r) => r.state === s).length;
  const lastAccounted = rows.filter((r) => r.at).reduce<Date | null>((m, r) => (!m || r.at! > m ? r.at! : m), null);
  return {
    alert: a,
    summary: { total: rows.length, safe: count('SAFE'), needHelp: count('NEED_HELP'), away: count('AWAY'), unaccounted: count('UNACCOUNTED') },
    /** Seconds from raising to the last person accounted for — once nobody is unaccounted. */
    allAccountedInSeconds: count('UNACCOUNTED') === 0 && lastAccounted ? Math.round((lastAccounted.getTime() - a.raisedAt.getTime()) / 1000) : null,
    rows,
  };
}

/** A warden marks someone they have seen (or found needing help). */
export async function markPerson(alertId: string, studentProfileId: string, status: 'SAFE' | 'NEED_HELP', actorId: string, note?: string | null) {
  const a = await db.emergencyAlert.findFirst({ where: { id: alertId }, select: { closedAt: true } });
  if (!a) throw new NotFoundError('Alert not found');
  if (a.closedAt) throw new ConflictError('This alert is closed');
  if (!(await db.studentProfile.findFirst({ where: { id: studentProfileId }, select: { id: true } }))) throw new NotFoundError('Employee not found');
  return db.emergencyAck.upsert({
    where: { alertId_studentProfileId: { alertId, studentProfileId } },
    create: { tenantId: getTenantIdOrThrow(), alertId, studentProfileId, status, source: 'WARDEN', note: note ?? null, byUserId: actorId },
    update: { status, source: 'WARDEN', note: note ?? null, byUserId: actorId, at: new Date() },
  });
}

/** All clear: closes it (a drill with what was seen), and says so to everyone who was told. */
export async function closeAlert(alertId: string, actorId: string, observations?: string | null) {
  const a = await db.emergencyAlert.findFirst({ where: { id: alertId } });
  if (!a) throw new NotFoundError('Alert not found');
  if (a.closedAt) throw new ConflictError('Already closed');
  const closed = await db.emergencyAlert.update({ where: { id: alertId }, data: { closedAt: new Date(), closedById: actorId, observations: observations ?? null } });
  const tenantId = getTenantIdOrThrow();
  inBackground('push: all clear', async () => {
    const residents = await audienceMembers(tenantId, { propertyId: a.propertyId });
    await pushTo(tenantId, 'EMERGENCY', `${alertId}:clear`, residents.map((r) => r.userId), { title: `${a.isDrill ? 'Drill over' : 'All clear'}: ${a.title}`, body: a.isDrill ? 'Thank you. The drill is over.' : 'The emergency is over. Thank you.', data: { alertId } });
  });
  return closed;
}

/** The history: real alerts and drills, with their headcount at the end. */
export async function listAlerts(f: { isDrill?: boolean; propertyId?: string }) {
  const rows = await db.emergencyAlert.findMany({ where: { ...(f.isDrill !== undefined ? { isDrill: f.isDrill } : {}), ...(f.propertyId ? { OR: [{ propertyId: f.propertyId }, { propertyId: null }] } : {}) }, orderBy: { raisedAt: 'desc' }, take: 100 });
  const acks = await db.emergencyAck.groupBy({ by: ['alertId', 'status'], where: { alertId: { in: rows.map((r) => r.id) } }, _count: { _all: true } });
  return rows.map((r) => ({
    ...r,
    safe: acks.find((x) => x.alertId === r.id && x.status === 'SAFE')?._count._all ?? 0,
    needHelp: acks.find((x) => x.alertId === r.id && x.status === 'NEED_HELP')?._count._all ?? 0,
    minutesOpen: r.closedAt ? Math.round((r.closedAt.getTime() - r.raisedAt.getTime()) / 60_000) : null,
  }));
}

// ── The emergency team ──────────────────────────────────────────────────────

export interface TeamInput {
  name: string;
  phone: string;
  role: string;
  propertyId?: string | null;
  userId?: string | null;
  shiftId?: string | null;
  trainedOn?: Date | null;
  validUntil?: Date | null;
  certificate?: string | null;
  isActive?: boolean;
}

export async function team(includeInactive = false) {
  const rows = await db.emergencyTeamMember.findMany({ where: includeInactive ? {} : { isActive: true }, orderBy: [{ role: 'asc' }, { name: 'asc' }], take: 500 });
  const soon = Date.now() + 30 * 86_400_000;
  return rows.map((m) => ({ ...m, training: !m.validUntil ? 'UNKNOWN' : m.validUntil.getTime() < Date.now() ? 'EXPIRED' : m.validUntil.getTime() < soon ? 'DUE' : 'VALID' }));
}

export async function addMember(input: TeamInput) {
  if (input.trainedOn && input.validUntil && input.validUntil < input.trainedOn) throw new BadRequestError('Valid until must be after the training date');
  return db.emergencyTeamMember.create({ data: { ...input, tenantId: getTenantIdOrThrow() } });
}

export async function updateMember(id: string, input: Partial<TeamInput>) {
  if (!(await db.emergencyTeamMember.findFirst({ where: { id }, select: { id: true } }))) throw new NotFoundError('Team member not found');
  return db.emergencyTeamMember.update({ where: { id }, data: input });
}
