import { PaymentStatus, Prisma, Role, StudentRequestStatus } from '@prisma/client';
import { invoiceKindWord, isDormitoryTenant } from '../../lib/invoice-words';
import { noticeAudienceUserIds, noticeIsTargeted } from '../communication/audience';
import { effectivePermissions, type Permission } from '../../lib/permissions';
import { prismaUnscoped } from '../../lib/prisma';
import { runWithTenantContext } from '../../lib/tenantContext';
import { isEmailConfigured, sendEmail, type EmailAttachment } from '../../lib/email';
import { BRAND_SELECT, brandFromSettings } from '../../lib/email-brand';
import { periodEnd } from '../../lib/period';
import {
  invoiceRaisedEmail,
  noticeEmail,
  requestClosedEmail,
  paymentFailedEmail,
  paymentReceivedEmail,
  settlementSharedEmail,
  type EmailMessage,
  type InvoiceFacts,
} from '../../lib/email-templates';
import { buildInvoicePdf, invoiceNumber, paymentNumber } from '../billing/invoice-pdf.service';
import { sendPush, type PushMessage } from '../../lib/push';
import { dropDeadTokens, tokensByUser } from '../devices/devices.service';
import { recordInbox } from '../inbox/inbox.service';
import { sendWhatsApp } from '../../lib/whatsapp';

/**
 * The emails the product sends on its own: a payment recorded, a payment
 * reversed, a new invoice, an important notice — each also pushed to the
 * person's phone — plus the push-only alerts below them: gate passes,
 * requests and visitors.
 *
 * Every entry point here is meant to be called AFTER the response has been
 * sent (`void notify…()`), so a slow or down mail provider never delays the
 * office. They therefore take the tenantId explicitly and use the unscoped
 * client, exactly as the reminder engine does — there is no request context
 * to lean on by the time they run.
 *
 * NotificationLog is claimed before each send with a unique key, so a retry,
 * a double click or two racing requests can never email the same person
 * twice about the same thing. The log is also what Settings shows as the
 * "recent emails" audit.
 */

export type NotificationKind =
  | 'PAYMENT_RECEIVED'
  | 'PAYMENT_FAILED'
  | 'INVOICE_RAISED'
  | 'NOTICE'
  | 'SETTLEMENT'
  // Push only:
  | 'PASS_AWAITING_GUARDIAN'
  | 'PASS_DECIDED'
  | 'PASS_OVERDUE'
  | 'REQUEST_NEW'
  | 'REQUEST_UPDATED'
  | 'REQUEST_ASSIGNED'
  | 'ARRIVAL_CHECK_IN'
  | 'LEAVE_PLANT_PENDING'
  // Sprint 2 (TEPL)
  | 'REQUEST_CLOSED'
  | 'REQUEST_ESCALATED'
  | 'INCIDENT_RECORDED'
  | 'PARCEL_ARRIVED'
  | 'LOST_FOUND_CLAIM'
  | 'LOST_FOUND_RETURNED'
  | 'LOST_FOUND_MATCH'
  // Sprint 3 (TEPL)
  | 'CLEANING_MISSED'
  | 'WORK_ORDER_ASSIGNED'
  | 'LAUNDRY_READY'
  | 'VISITOR_ARRIVED'
  // Sprint 4 (TEPL)
  | 'CURFEW_BREACH'
  | 'OUTING_REQUESTED'
  | 'OUTING_DECIDED'
  | 'BUS_OVERDUE'
  | 'ENERGY_HIGH_USE'
  // Sprint 5 (TEPL)
  | 'EVENT_PUBLISHED'
  | 'EVENT_REMINDER'
  | 'EMERGENCY'
  // Sprint 6 (TEPL)
  | 'MEDICAL_APPOINTMENT'
  | 'ASSISTANCE_REQUEST'
  | 'MEDICAL_ACCESS'
  // Sprint 7 (TEPL)
  | 'COMPLIANCE_DUE'
  | 'COMPLIANCE_ACTION';

const rupees = (n: number) => `₹${n.toLocaleString('en-IN')}`;

const dayLabel = (d: Date | null | undefined) =>
  d ? d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' }) : null;
const monthLabel = (p: string) => new Date(`${p}-01T00:00:00Z`).toLocaleDateString('en-IN', { month: 'long', year: 'numeric', timeZone: 'UTC' });
const monthShort = (p: string) => new Date(`${p}-01T00:00:00Z`).toLocaleDateString('en-IN', { month: 'short', year: 'numeric', timeZone: 'UTC' });
const METHOD_LABEL: Record<string, string> = { CASH: 'Cash', UPI: 'UPI', CARD: 'Card', BANK_TRANSFER: 'Bank transfer', CHEQUE: 'Cheque', OTHER: 'Other', ONLINE: 'Online (Razorpay)' };

export function periodLabel(periodMonth: string, cycleMonths: number): string {
  return cycleMonths > 1 ? `${monthShort(periodMonth)} – ${monthShort(periodEnd(periodMonth, cycleMonths))}` : monthLabel(periodMonth);
}

async function firmFor(tenantId: string) {
  const [settings, tenant] = await Promise.all([
    prismaUnscoped.tenantSettings.findUnique({
      where: { tenantId },
      select: { ...BRAND_SELECT, notifyPaymentEmail: true, notifyInvoiceEmail: true, notifyNoticeEmail: true },
    }),
    prismaUnscoped.tenant.findUnique({ where: { id: tenantId }, select: { name: true } }),
  ]);
  return {
    firm: settings?.billingFirmName?.trim() || tenant?.name || 'HostelCare',
    brand: brandFromSettings(settings, tenant?.name),
    contact: [settings?.billingPhone, settings?.billingEmail].filter(Boolean).join(' / ') || null,
    notifyPayment: settings?.notifyPaymentEmail ?? true,
    notifyInvoice: settings?.notifyInvoiceEmail ?? true,
    notifyNotice: settings?.notifyNoticeEmail ?? true,
  };
}

/**
 * Claim the log slot, send, record the outcome. Returns false when the slot
 * was already taken (someone else sent it) or there was no address.
 */
async function deliver(
  tenantId: string,
  kind: NotificationKind,
  refId: string,
  to: { id: string; email: string | null },
  message: EmailMessage,
  attachments: EmailAttachment[] = [],
): Promise<boolean> {
  if (!to.email) return false;
  let logId: string;
  try {
    const row = await prismaUnscoped.notificationLog.create({
      data: { tenantId, kind, refId, userId: to.id, email: to.email, status: 'PENDING' },
      select: { id: true },
    });
    logId = row.id;
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return false;
    throw e;
  }
  try {
    const result = await sendEmail(to.email, message.subject, message.text, message.html, attachments);
    await prismaUnscoped.notificationLog.update({
      where: { id: logId },
      data: { status: result.mode === 'log' ? 'DRY_RUN' : result.sent ? 'SENT' : 'FAILED', error: result.sent || result.mode === 'log' ? null : `provider:${result.mode}` },
    });
    return result.sent || result.mode === 'log';
  } catch (e) {
    await prismaUnscoped.notificationLog.update({ where: { id: logId }, data: { status: 'FAILED', error: String(e).slice(0, 300) } }).catch(() => {});
    return false;
  }
}

/**
 * Push to each user's phones, once per (kind, ref, user) — claimed in the
 * same log as email, on the PUSH channel, so a retry never buzzes twice.
 * Users with no phone registered are skipped without a log row. Push does
 * not follow the tenant's email switches: those are about email, and the
 * person chose push themselves when they allowed notifications on the phone.
 * Returns how many users it reached.
 */
export async function pushTo(
  tenantId: string,
  kind: NotificationKind,
  refId: string,
  userIds: string[],
  message: Omit<PushMessage, 'data'> & { data?: Record<string, string> },
): Promise<number> {
  // The inbox keeps every alert, phone or no phone (employee hostels).
  await recordInbox(tenantId, kind, refId, userIds, message).catch((err) => console.error('[inbox] record failed:', err)); // eslint-disable-line no-console
  const devices = await tokensByUser([...new Set(userIds)]);
  let reached = 0;
  for (const [userId, tokens] of devices) {
    let logId: string;
    try {
      const row = await prismaUnscoped.notificationLog.create({
        data: { tenantId, kind, refId, userId, email: '', channel: 'PUSH', status: 'PENDING' },
        select: { id: true },
      });
      logId = row.id;
    } catch (e) {
      if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') continue;
      throw e;
    }
    const result = await sendPush(tokens, { title: message.title, body: message.body, data: { kind, refId, ...message.data }, channelId: message.channelId });
    await dropDeadTokens(result.deadTokens).catch(() => {});
    await prismaUnscoped.notificationLog
      .update({
        where: { id: logId },
        data: {
          status: result.mode === 'log' ? 'DRY_RUN' : result.sent > 0 ? 'SENT' : 'FAILED',
          error: result.mode === 'fcm-error' ? 'provider:fcm' : result.sent === 0 && result.mode === 'fcm' ? 'no live device' : null,
        },
      })
      .catch(() => {});
    if (result.sent > 0) reached++;
  }
  return reached;
}

async function invoiceFacts(invoiceId: string) {
  const inv = await prismaUnscoped.invoice.findUnique({
    where: { id: invoiceId },
    include: {
      payments: { where: { status: PaymentStatus.CLEARED }, select: { amount: true } },
      student: { include: { user: { select: { id: true, name: true, email: true } } } },
    },
  });
  if (!inv) return null;
  const paid = inv.payments.reduce((n, p) => n + p.amount, 0);
  const facts: InvoiceFacts = {
    number: invoiceNumber(inv.id, inv.periodMonth),
    kind: invoiceKindWord(inv.type, await isDormitoryTenant(inv.tenantId)),
    periodLabel: periodLabel(inv.periodMonth, inv.cycleMonths),
    amount: inv.amount,
    paid,
    balance: Math.max(0, inv.amount - paid),
    dueDate: dayLabel(inv.dueDate),
  };
  return { inv, facts };
}

/** Render the receipt for the attachment. Any failure means "no attachment", never "no email". */
async function receiptPdf(tenantId: string, invoiceId: string, userId: string): Promise<EmailAttachment[]> {
  try {
    const { buffer, filename } = await runWithTenantContext({ tenantId, userId, role: Role.HOSTEL_ADMIN }, () => buildInvoicePdf(invoiceId));
    return [{ filename, content: buffer }];
  } catch {
    return [];
  }
}

// ── Entry points ─────────────────────────────────────────────────────────────

export async function notifyPaymentRecorded(tenantId: string, paymentId: string): Promise<void> {
  const { firm, brand, notifyPayment } = await firmFor(tenantId);
  const payment = await prismaUnscoped.payment.findUnique({ where: { id: paymentId } });
  if (!payment || payment.tenantId !== tenantId) return;
  const loaded = await invoiceFacts(payment.invoiceId);
  if (!loaded) return;
  const { inv, facts } = loaded;
  const user = inv.student.user;
  await pushTo(tenantId, 'PAYMENT_RECEIVED', payment.id, [user.id], {
    title: 'Payment received',
    body: `${rupees(payment.amount)} for ${facts.kind} · ${facts.periodLabel}. ${facts.balance > 0 ? `${rupees(facts.balance)} still due.` : 'Paid in full — thank you.'}`,
    data: { invoiceId: inv.id },
  });
  if (!notifyPayment) return;
  const attachments = user.email && isEmailConfigured() ? await receiptPdf(tenantId, inv.id, user.id) : [];
  const message = paymentReceivedEmail({
    firm,
    brand,
    studentName: user.name,
    amount: payment.amount,
    paidOn: dayLabel(payment.paidAt)!,
    method: METHOD_LABEL[payment.method] ?? payment.method,
    reference: payment.reference,
    paymentId: paymentNumber(payment.id),
    invoice: facts,
    receiptAttached: attachments.length > 0,
  });
  await deliver(tenantId, 'PAYMENT_RECEIVED', payment.id, user, message, attachments);
}

export async function notifyPaymentFailed(tenantId: string, paymentId: string): Promise<void> {
  const { firm, brand, contact, notifyPayment } = await firmFor(tenantId);
  const payment = await prismaUnscoped.payment.findUnique({ where: { id: paymentId } });
  if (!payment || payment.tenantId !== tenantId || payment.status !== PaymentStatus.FAILED) return;
  const loaded = await invoiceFacts(payment.invoiceId);
  if (!loaded) return;
  const { inv, facts } = loaded;
  await pushTo(tenantId, 'PAYMENT_FAILED', payment.id, [inv.student.user.id], {
    title: 'Payment did not go through',
    body: `${rupees(payment.amount)} for ${facts.kind} · ${facts.periodLabel} was reversed${payment.failureReason ? `: ${payment.failureReason}` : ''}. ${rupees(facts.balance)} is due.`,
    data: { invoiceId: inv.id },
  });
  if (!notifyPayment) return;
  const message = paymentFailedEmail({
    firm,
    brand,
    studentName: inv.student.user.name,
    amount: payment.amount,
    paidOn: dayLabel(payment.paidAt)!,
    method: METHOD_LABEL[payment.method] ?? payment.method,
    reference: payment.reference,
    paymentId: paymentNumber(payment.id),
    reason: payment.failureReason,
    invoice: facts,
    contact,
  });
  await deliver(tenantId, 'PAYMENT_FAILED', payment.id, inv.student.user, message);
}

/** One "fee due" email per new invoice. Sequential: a generate run can be hundreds. */
export async function notifyInvoicesRaised(tenantId: string, invoiceIds: string[]): Promise<void> {
  if (invoiceIds.length === 0) return;
  const { firm, brand, notifyInvoice } = await firmFor(tenantId);
  for (const id of invoiceIds) {
    const loaded = await invoiceFacts(id);
    if (!loaded) continue;
    const { inv, facts } = loaded;
    await pushTo(tenantId, 'INVOICE_RAISED', inv.id, [inv.student.user.id], {
      title: `${facts.kind} due · ${facts.periodLabel}`,
      body: `${rupees(facts.balance)}${facts.dueDate ? ` by ${facts.dueDate}` : ''}. Pay from the app.`,
      data: { invoiceId: inv.id },
    });
    if (!notifyInvoice) continue;
    const message = invoiceRaisedEmail({ firm, brand, studentName: inv.student.user.name, invoice: facts, cycleMonths: inv.cycleMonths });
    await deliver(tenantId, 'INVOICE_RAISED', inv.id, inv.student.user, message);
  }
}

/** An important notice goes to everyone in the hostel with an email address, except the poster. */
export async function notifyNoticePosted(tenantId: string, noticeId: string): Promise<void> {
  const { firm, brand, notifyNotice } = await firmFor(tenantId);
  const notice = await prismaUnscoped.notice.findUnique({ where: { id: noticeId } });
  if (!notice || notice.tenantId !== tenantId || !notice.important) return;

  const everyone = await prismaUnscoped.user.findMany({
    where: {
      tenantId,
      id: { not: notice.postedById },
      // A mess notice concerns residents and the kitchen, not every warden.
      ...(notice.category === 'MESS' ? { role: { in: [Role.STUDENT, Role.MESS_ADMIN, Role.HOSTEL_ADMIN] } } : {}),
    },
    select: { id: true, name: true, email: true, role: true },
    orderBy: { createdAt: 'asc' },
  });
  // Sprint 4 (TEPL): a notice for one block, floor, shift or department reaches only those residents.
  const audience = noticeIsTargeted(notice) ? new Set(await noticeAudienceUserIds(tenantId, notice)) : null;
  const recipients = audience ? everyone.filter((u) => u.role !== Role.STUDENT || audience.has(u.id)) : everyone;

  await pushTo(
    tenantId,
    'NOTICE',
    notice.id,
    recipients.map((r) => r.id),
    { title: notice.title, body: notice.body.length > 140 ? `${notice.body.slice(0, 137)}…` : notice.body, data: { noticeId: notice.id } },
  );
  if (!notifyNotice) return;
  let sent = 0;
  for (const r of recipients) {
    const message = noticeEmail({ firm, brand, recipientName: r.name, title: notice.title, body: notice.body, postedBy: notice.postedByName, category: notice.category });
    if (await deliver(tenantId, 'NOTICE', notice.id, r, message)) sent++;
  }
  await prismaUnscoped.notice.update({ where: { id: notice.id }, data: { emailedAt: new Date(), emailedCount: sent } }).catch(() => {});
}

/** The move-out settlement, with the statement attached. Once per share. */
export async function notifySettlementShared(tenantId: string, moveOutId: string): Promise<void> {
  const { firm, brand } = await firmFor(tenantId);
  const m = await prismaUnscoped.moveOut.findUnique({ where: { id: moveOutId }, include: { settlement: true, student: { include: { user: { select: { id: true, name: true, email: true } } } } } });
  if (!m?.settlement?.sharedAt || m.tenantId !== tenantId) return;
  const s = m.settlement;
  const sharedAt = m.settlement.sharedAt;
  const day = (d: Date) => d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', timeZone: 'UTC' });
  let attachments: EmailAttachment[] = [];
  if (m.student.user.email && isEmailConfigured()) {
    try {
      const { buildSettlementPdf } = await import('../moveouts/settlement-pdf.service');
      const { buffer, filename } = await runWithTenantContext({ tenantId, userId: m.student.user.id, role: Role.HOSTEL_ADMIN }, () => buildSettlementPdf(moveOutId));
      attachments = [{ filename, content: buffer }];
    } catch {
      attachments = [];
    }
  }
  const message = settlementSharedEmail({
    firm,
    brand,
    studentName: m.student.user.name,
    lastDay: day(m.lastDay),
    depositHeld: s.depositHeld,
    dues: Math.max(0, s.duesBalance - s.prorataCredit),
    deductions: (s.deductions as { label: string; amount: number }[]) ?? [],
    refundDue: s.refundDue,
    shortfall: s.shortfall,
    promisedDate: day(s.promisedDate),
    attached: attachments.length > 0,
  });
  // Keyed on the share time, so a reopen-and-share-again notifies again.
  await pushTo(tenantId, 'SETTLEMENT', `${moveOutId}:${sharedAt.getTime()}`, [m.student.user.id], {
    title: 'Your move-out settlement',
    body: s.refundDue > 0 ? `${rupees(s.refundDue)} to be refunded by ${day(s.promisedDate)}. Open it to approve or raise a question.` : `See the breakdown and approve it, or raise a question.`,
    data: { moveOutId },
  });
  await deliver(tenantId, 'SETTLEMENT', `${moveOutId}:${sharedAt.getTime()}`, m.student.user, message, attachments);
}

// ── Push-only alerts ─────────────────────────────────────────────────────────

/** Staff whose effective permissions include [perm] — custom roles included. */
export async function staffWith(tenantId: string, perm: Permission): Promise<string[]> {
  const staff = await prismaUnscoped.user.findMany({
    where: { tenantId, role: { in: [Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN] } },
    select: { id: true, role: true, customRole: { select: { permissions: true } } },
  });
  return staff.filter((u) => effectivePermissions(u.role, u.customRole?.permissions).includes(perm)).map((u) => u.id);
}

async function guardiansOf(studentProfileId: string): Promise<string[]> {
  const links = await prismaUnscoped.guardianLink.findMany({ where: { studentProfileId }, select: { userId: true } });
  return links.map((l) => l.userId);
}

const passInclude = { student: { select: { id: true, user: { select: { id: true, name: true } } } } } as const;
const whenIST = (d: Date) => d.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: 'numeric', minute: '2-digit', timeZone: 'Asia/Kolkata' });

/** A pass that needs the guardian's yes: to every guardian of the student. */
export async function notifyPassAwaitingGuardian(tenantId: string, passId: string): Promise<void> {
  const pass = await prismaUnscoped.gatePass.findUnique({ where: { id: passId }, include: passInclude });
  if (!pass || pass.tenantId !== tenantId) return;
  await pushTo(tenantId, 'PASS_AWAITING_GUARDIAN', pass.id, await guardiansOf(pass.studentProfileId), {
    title: `${pass.student.user.name} asks to go out`,
    body: `${pass.destination ? `To ${pass.destination}, ` : ''}${whenIST(pass.validFrom)} to ${whenIST(pass.validTo)}. Approve or decline in the app.`,
    data: { passId: pass.id, studentProfileId: pass.studentProfileId },
  });
}

/** The guardian's answer, back to the student. */
export async function notifyPassDecided(tenantId: string, passId: string): Promise<void> {
  const pass = await prismaUnscoped.gatePass.findUnique({ where: { id: passId }, include: passInclude });
  if (!pass || pass.tenantId !== tenantId) return;
  const approved = !!pass.guardianApprovedAt;
  await pushTo(tenantId, 'PASS_DECIDED', pass.id, [pass.student.user.id], {
    title: approved ? 'Your guardian approved your pass' : 'Your guardian declined your pass',
    body: approved
      ? `Your gate pass is ready${pass.destination ? ` for ${pass.destination}` : ''}. Show its QR at the gate.`
      : pass.guardianNote ?? 'Ask your guardian or the warden.',
    data: { passId: pass.id },
  });
}

/**
 * A pass still out past its return time: the student, their guardians and
 * the staff who run the gate. Called by the hourly late-return check, once
 * per pass.
 */
export async function notifyPassOverdue(tenantId: string, passId: string): Promise<void> {
  const pass = await prismaUnscoped.gatePass.findUnique({ where: { id: passId }, include: passInclude });
  if (!pass || pass.tenantId !== tenantId) return;
  const due = whenIST(pass.validTo);
  await pushTo(tenantId, 'PASS_OVERDUE', pass.id, [pass.student.user.id], {
    title: 'You are past your return time',
    body: `Your pass was due back ${due}. Head back, or let the warden know.`,
    data: { passId: pass.id },
  });
  const others = [...(await guardiansOf(pass.studentProfileId)), ...(await staffWith(tenantId, 'MANAGE_GATE'))];
  await pushTo(tenantId, 'PASS_OVERDUE', pass.id, others, {
    title: `${pass.student.user.name} is late back`,
    body: `Due back ${due}${pass.destination ? ` from ${pass.destination}` : ''}.`,
    data: { passId: pass.id, studentProfileId: pass.studentProfileId },
  });
}

const REQUEST_STATUS_WORDS: Partial<Record<StudentRequestStatus, string>> = {
  IN_PROGRESS: 'is being looked at',
  APPROVED: 'was approved',
  REJECTED: 'was declined',
  RESOLVED: 'was resolved',
  OPEN: 'was reopened',
};

/** A student's new request: to the staff who handle requests. */
export async function notifyRequestCreated(tenantId: string, requestId: string): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({ where: { id: requestId }, include: { student: { select: { user: { select: { name: true } } } } } });
  if (!r || r.tenantId !== tenantId) return;
  await pushTo(tenantId, 'REQUEST_NEW', r.id, await staffWith(tenantId, 'MANAGE_STUDENTS'), {
    // An anonymous complaint never carries the name, not even in a notification.
    title: r.anonymous ? 'New anonymous complaint' : `New request from ${r.student.user.name}`,
    body: r.subject,
    data: { requestId: r.id },
  });
}

/**
 * The student's request moved: a new status, or a reply from the office.
 * Each change is its own push — a status can come round again, and replies
 * pile up — so the log key carries the change, not just the request.
 */
export async function notifyRequestUpdated(tenantId: string, requestId: string, change: { status: StudentRequestStatus } | { replyId: string }): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({ where: { id: requestId }, include: { student: { select: { user: { select: { id: true } } } } } });
  if (!r || r.tenantId !== tenantId) return;
  if ('status' in change) {
    const words = REQUEST_STATUS_WORDS[change.status];
    if (!words) return;
    await pushTo(tenantId, 'REQUEST_UPDATED', `${r.id}:${change.status}:${Date.now()}`, [r.student.user.id], {
      title: `Your request ${words}`,
      body: r.subject,
      data: { requestId: r.id },
    });
  } else {
    await pushTo(tenantId, 'REQUEST_UPDATED', `${r.id}:reply:${change.replyId}`, [r.student.user.id], {
      title: 'New reply on your request',
      body: r.subject,
      data: { requestId: r.id },
    });
  }
}

// ── Sprint 2 (TEPL): grievance desk, discipline, parcels, lost and found ────

/**
 * A complaint or repair closed: an email and a WhatsApp message to the
 * employee, on top of the push the status change already sent. Once per
 * close (the log key carries the close time), and only for a real address.
 */
export async function notifyRequestClosed(tenantId: string, requestId: string): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({
    where: { id: requestId },
    select: { id: true, tenantId: true, subject: true, status: true, resolvedAt: true, student: { select: { user: { select: { id: true, name: true, email: true, phone: true, hasLogin: true } } } }, replies: { where: { author: { role: { not: Role.STUDENT } } }, orderBy: { createdAt: 'desc' }, take: 1, select: { body: true } } },
  });
  if (!r || r.tenantId !== tenantId || (r.status !== StudentRequestStatus.RESOLVED && r.status !== StudentRequestStatus.REJECTED)) return;
  const user = r.student.user;
  const ref = `${r.id}:${r.resolvedAt?.getTime() ?? Date.now()}`;
  const { firm, brand } = await firmFor(tenantId);
  if (user.hasLogin && user.email) {
    await deliver(tenantId, 'REQUEST_CLOSED', ref, user, requestClosedEmail({ firm, brand, recipientName: user.name, subject: r.subject, outcome: r.status, lastReply: r.replies[0]?.body ?? null }));
  }
  if (user.phone) {
    const words = r.status === StudentRequestStatus.RESOLVED ? 'was resolved' : 'was closed';
    await sendWhatsApp(user.phone, `${firm}: your request "${r.subject}" ${words}. Open the app to see the thread and rate how it was handled.`, { tenantId, userId: user.id, purpose: 'REQUEST_CLOSED' }).catch(() => undefined);
  }
}

/** Overdue: level 1 to the managers and whoever has it; level 2, a day later, to the managers again. */
export async function notifyRequestEscalated(tenantId: string, requestId: string, level: number): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({ where: { id: requestId }, select: { id: true, tenantId: true, subject: true, type: true, category: true, dueBy: true, assigneeId: true } });
  if (!r || r.tenantId !== tenantId) return;
  const managers = await staffWith(tenantId, 'MANAGE_STAFF');
  const to = level === 1 && r.assigneeId ? [...managers, r.assigneeId] : managers;
  await pushTo(tenantId, 'REQUEST_ESCALATED', `${r.id}:${level}`, to, {
    title: level === 1 ? `Overdue: ${r.subject}` : `Still overdue a day later: ${r.subject}`,
    body: `Its target was ${r.dueBy ? r.dueBy.toLocaleString('en-IN', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', timeZone: 'Asia/Kolkata' }) : 'set'}. Escalation level ${level}.`,
    data: { requestId: r.id },
  });
}

/** An incident on their record — to the employee, so nothing is kept from them. */
export async function notifyIncidentRecorded(tenantId: string, incidentId: string): Promise<void> {
  const i = await prismaUnscoped.disciplineIncident.findUnique({ where: { id: incidentId }, select: { id: true, tenantId: true, category: true, action: true, student: { select: { userId: true } } } });
  if (!i || i.tenantId !== tenantId) return;
  await pushTo(tenantId, 'INCIDENT_RECORDED', i.id, [i.student.userId], {
    title: 'An incident was recorded on your hostel record',
    body: i.action !== 'NONE' ? `Action: ${i.action.replace(/_/g, ' ').toLowerCase()}. See it in the app.` : 'See it in the app.',
    data: { incidentId: i.id },
  });
}

/** A parcel at the gate — to the employee it is for. */
export async function notifyParcelArrived(tenantId: string, parcelId: string): Promise<void> {
  const p = await prismaUnscoped.parcel.findUnique({ where: { id: parcelId }, select: { id: true, tenantId: true, courier: true, student: { select: { userId: true } } } });
  if (!p || p.tenantId !== tenantId) return;
  await pushTo(tenantId, 'PARCEL_ARRIVED', p.id, [p.student.userId], {
    title: 'A parcel is waiting for you at the gate',
    body: p.courier ? `From ${p.courier}. Collect it from security.` : 'Collect it from security.',
    data: { parcelId: p.id },
  });
}

/** Lost and found: a claim to the desk, a return to the claimant, or a found item like one they lost. */
export async function notifyLostFound(tenantId: string, itemId: string, what: 'CLAIM' | 'RETURNED' | 'MATCH', userIds?: string[]): Promise<void> {
  const item = await prismaUnscoped.lostFoundItem.findUnique({ where: { id: itemId }, select: { id: true, tenantId: true, title: true, claimantProfileId: true } });
  if (!item || item.tenantId !== tenantId) return;
  if (what === 'CLAIM') {
    const desk = [...new Set([...(await staffWith(tenantId, 'MANAGE_GATE')), ...(await staffWith(tenantId, 'MANAGE_STUDENTS'))])];
    await pushTo(tenantId, 'LOST_FOUND_CLAIM', `${item.id}:${item.claimantProfileId}`, desk, { title: `Someone says the ${item.title} is theirs`, body: 'Check their ID and hand it over at the desk.', data: { itemId: item.id } });
  } else if (what === 'RETURNED' && item.claimantProfileId) {
    const p = await prismaUnscoped.studentProfile.findUnique({ where: { id: item.claimantProfileId }, select: { userId: true } });
    if (p) await pushTo(tenantId, 'LOST_FOUND_RETURNED', item.id, [p.userId], { title: `${item.title}: handed back to you`, body: 'Marked returned at the desk.', data: { itemId: item.id } });
  } else if (what === 'MATCH' && userIds?.length) {
    await pushTo(tenantId, 'LOST_FOUND_MATCH', item.id, userIds, { title: `Found: ${item.title}`, body: 'Something like what you lost was handed in. See Lost and found in the app.', data: { itemId: item.id } });
  }
}

// ── Sprint 3 (TEPL): housekeeping, work orders, laundry ─────────────────────

/** Cleaning not done by the end of its day — to the housekeeping supervisors, once a day. */
export async function notifyCleaningMissed(tenantId: string, day: string, count: number): Promise<void> {
  await pushTo(tenantId, 'CLEANING_MISSED', day, await staffWith(tenantId, 'MANAGE_HOUSEKEEPING'), {
    title: `${count} cleaning task${count === 1 ? '' : 's'} missed`,
    body: 'Not done by the end of the day. See the cleaning board.',
    data: { day },
  });
}

/** A work order handed to someone — to them. */
export async function notifyWorkOrderAssigned(tenantId: string, workOrderId: string): Promise<void> {
  const w = await prismaUnscoped.workOrder.findUnique({ where: { id: workOrderId }, select: { id: true, tenantId: true, title: true, assigneeId: true, priority: true } });
  if (!w || w.tenantId !== tenantId || !w.assigneeId) return;
  await pushTo(tenantId, 'WORK_ORDER_ASSIGNED', `${w.id}:${w.assigneeId}`, [w.assigneeId], {
    title: w.priority === 'HIGH' ? 'Urgent work order for you' : 'A work order was handed to you',
    body: w.title,
    data: { workOrderId: w.id },
  });
}

/** Laundry back from the vendor — to each bag's owner. */
export async function notifyLaundryReady(tenantId: string, orderIds: string[]): Promise<void> {
  const orders = await prismaUnscoped.laundryOrder.findMany({ where: { id: { in: orderIds }, tenantId }, select: { id: true, bagNo: true, studentProfileId: true } });
  const users = new Map((await prismaUnscoped.studentProfile.findMany({ where: { id: { in: orders.map((o) => o.studentProfileId) } }, select: { id: true, userId: true } })).map((p) => [p.id, p.userId]));
  for (const o of orders) {
    const userId = users.get(o.studentProfileId);
    if (userId) await pushTo(tenantId, 'LAUNDRY_READY', o.id, [userId], { title: 'Your laundry is back', body: o.bagNo ? `Bag ${o.bagNo} is ready to collect.` : 'Ready to collect.', data: { laundryOrderId: o.id } });
  }
}

/** Sprint 1 (TEPL): an employee's first punch moved them into the bed held for them — to the staff who onboard. */
export async function notifyArrivalCheckIn(tenantId: string, studentProfileId: string, bed: { room: string; bed: string }): Promise<void> {
  const p = await prismaUnscoped.studentProfile.findUnique({ where: { id: studentProfileId }, select: { tenantId: true, user: { select: { name: true } } } });
  if (!p || p.tenantId !== tenantId) return;
  await pushTo(tenantId, 'ARRIVAL_CHECK_IN', studentProfileId, await staffWith(tenantId, 'MANAGE_STUDENTS'), {
    title: `${p.user.name} has arrived`,
    body: `Checked into room ${bed.room}, bed ${bed.bed} on their first punch.`,
    data: { studentProfileId },
  });
}

/** Sprint 1 (TEPL): a leave the hostel approved, now waiting for the plant — to the department's approvers. */
export async function notifyLeavePlantPending(tenantId: string, requestId: string): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({ where: { id: requestId }, select: { id: true, tenantId: true, subject: true, fromDate: true, student: { select: { departmentId: true, user: { select: { name: true } } } } } });
  if (!r || r.tenantId !== tenantId || !r.student.departmentId) return;
  const approvers = await prismaUnscoped.departmentApprover.findMany({ where: { departmentId: r.student.departmentId }, select: { userId: true } });
  await pushTo(tenantId, 'LEAVE_PLANT_PENDING', r.id, approvers.map((a) => a.userId), {
    title: `Leave for ${r.student.user.name} needs your approval`,
    body: `${r.subject}${r.fromDate ? `, from ${dayLabel(r.fromDate)}` : ''}`,
    data: { requestId: r.id },
  });
}

/** Sprint 0 (TEPL): a request handed to a member of staff — to them. */
export async function notifyRequestAssigned(tenantId: string, requestId: string, assigneeId: string): Promise<void> {
  const r = await prismaUnscoped.studentRequest.findUnique({ where: { id: requestId }, select: { id: true, tenantId: true, subject: true } });
  if (!r || r.tenantId !== tenantId) return;
  await pushTo(tenantId, 'REQUEST_ASSIGNED', `${r.id}:${assigneeId}:${Date.now()}`, [assigneeId], {
    title: 'A task was handed to you',
    body: r.subject,
    data: { requestId: r.id },
  });
}

/** A visitor at the gate for a student — whether expected or logged on arrival. */
export async function notifyVisitorArrived(tenantId: string, visitorId: string): Promise<void> {
  const v = await prismaUnscoped.visitor.findUnique({ where: { id: visitorId }, include: { student: { select: { user: { select: { id: true } } } } } });
  if (!v || v.tenantId !== tenantId || !v.student) return;
  await pushTo(tenantId, 'VISITOR_ARRIVED', v.id, [v.student.user.id], {
    title: `${v.name} is at the gate`,
    body: v.purpose ? `Here to see you: ${v.purpose}.` : 'Here to see you.',
    data: { visitorId: v.id },
  });
}

/** Fire-and-forget wrapper: never let a mail failure surface as a request error. */
export function inBackground(label: string, work: () => Promise<void>): void {
  work().catch((err) => {
    // eslint-disable-next-line no-console
    console.error(`[notify] ${label} failed:`, err);
  });
}

/** The recent audit for Settings: what was emailed, to whom, and whether it went. */
export async function recentNotifications(tenantId: string, limit = 50) {
  return prismaUnscoped.notificationLog.findMany({
    // The Settings audit is of emails; pushes share the table on their own channel.
    where: { tenantId, channel: 'EMAIL' },
    orderBy: { createdAt: 'desc' },
    take: Math.min(Math.max(limit, 1), 200),
    select: { id: true, kind: true, refId: true, email: true, status: true, error: true, createdAt: true },
  });
}
