import { createHash, createHmac, randomUUID } from 'node:crypto';
import { CrmActivityType, CrmContactStatus, CrmDemoLanguage, CrmDemoStatus, CrmPropertyType, CrmStageKind, Prisma, Role } from '@prisma/client';
import { env, publicSiteUrl, publicWebUrl } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError, TooManyRequestsError } from '../../lib/errors';
import { crmEmail, demoIcs, demoOwnerEmail, type DemoOwnerEmailKind } from '../../lib/email-templates';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { getCrmSettings, superAdminCopyAddress, type CrmSettings } from './crm-settings.service';
import { crmUrl, deliver } from './crm-mail';
import { queueReminderCopy } from './crm-notify';
import { addToNurture, fullName, markTouched, unsubscribeUrl } from './crm-contacts.service';
import { ingestLead, type LeadInput } from './crm-leads.service';
import { dealRef, moveDeal } from './crm-deals.service';
import { demoStage, ensureStages, STAGE_KEYS } from './crm-stages.service';
import type { Actor } from './crm-users.service';

/**
 * Demo booking (Sprint L3): the website's own booking page instead of
 * Calendly.
 *
 * Each CRM member who takes demos sets weekly hours (India time), blocked
 * times and their Google Meet link. The website offers every slot at least
 * one of them has free; a booking goes to a free host (the lead owner
 * first), never twice to the same slot, and never past the daily cap.
 *
 * A booking makes the owner a CRM lead (source "Demo booking") with a deal
 * in "Demo scheduled". The owner gets a confirmation with a calendar invite
 * and a private link to move or cancel; reminders go the evening before and
 * an hour before, and the host hears 15 minutes before. After the demo the
 * host marks it Done (the owner gets the trial link and the deal moves to
 * "Demo done") or No-show (the owner gets the booking link; a second miss
 * sends the lead to the Nurture list).
 */

const IST_OFFSET = '+05:30';
const IST_MS = 330 * 60 * 1000;
const DAY_MS = 86_400_000;
/** The owner can move a booking this many times from their link. */
const MAX_OWNER_MOVES = 3;
const BED_PRICE_YEAR = 20 * 12;

export interface HoursRange {
  day: number;
  start: string;
  end: string;
}

// ── Time ───────────────────────────────────────────────────────────────────

const istDate = (d: Date) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 10);
const istWeekday = (date: string) => new Date(`${date}T12:00:00Z`).getUTCDay();
const atIst = (date: string, hhmm: string) => new Date(`${date}T${hhmm}:00${IST_OFFSET}`);
const addDays = (date: string, n: number) => new Date(Date.parse(`${date}T12:00:00Z`) + n * DAY_MS).toISOString().slice(0, 10);

/** "Tue 21 Oct, 11:00 am" — what every message calls a demo's time. */
export function fmtWhen(d: Date) {
  const day = d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', weekday: 'short', day: 'numeric', month: 'short' });
  const time = d.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour: 'numeric', minute: '2-digit' });
  return `${day}, ${time}`;
}

export const demoRef = (n: number) => `DEMO-${String(n).padStart(4, '0')}`;

// ── Hours and blocked time ─────────────────────────────────────────────────

function cleanHours(raw: unknown): HoursRange[] {
  if (!Array.isArray(raw)) return [];
  return raw
    .filter((r): r is HoursRange => !!r && typeof r === 'object' && Number.isInteger((r as HoursRange).day) && /^\d\d:\d\d$/.test((r as HoursRange).start) && /^\d\d:\d\d$/.test((r as HoursRange).end))
    .filter((r) => r.day >= 0 && r.day <= 6 && r.start < r.end)
    .sort((a, b) => a.day - b.day || a.start.localeCompare(b.start));
}

export async function getDemoHours(userId: string, now = new Date()) {
  const [h, blocks] = await Promise.all([
    prismaUnscoped.crmDemoHost.findUnique({ where: { userId } }),
    prismaUnscoped.crmDemoBlock.findMany({ where: { userId, endsAt: { gt: now } }, orderBy: { startsAt: 'asc' }, take: 100 }),
  ]);
  return {
    enabled: h?.enabled ?? false,
    meetUrl: h?.meetUrl ?? null,
    hours: cleanHours(h?.hours),
    blocks: blocks.map((b) => ({ id: b.id, startsAt: b.startsAt, endsAt: b.endsAt, note: b.note })),
  };
}

export async function setDemoHours(userId: string, input: { enabled?: boolean; meetUrl?: string | null; hours?: HoursRange[] }) {
  const hours = input.hours ? cleanHours(input.hours) : undefined;
  if (hours) {
    // Ranges on one day must not overlap; a slot would be offered twice.
    for (let i = 1; i < hours.length; i++) {
      if (hours[i].day === hours[i - 1].day && hours[i].start < hours[i - 1].end) throw new BadRequestError('Two time ranges on the same day overlap.', 'HOURS_OVERLAP');
    }
  }
  const current = await prismaUnscoped.crmDemoHost.findUnique({ where: { userId } });
  const meetUrl = input.meetUrl === undefined ? current?.meetUrl ?? null : input.meetUrl?.trim() || null;
  const enabled = input.enabled ?? current?.enabled ?? false;
  if (enabled && !meetUrl) throw new BadRequestError('Add your Google Meet link before taking demos.', 'MEET_LINK_REQUIRED');
  await prismaUnscoped.crmDemoHost.upsert({
    where: { userId },
    update: { enabled, meetUrl, ...(hours ? { hours: hours as unknown as Prisma.InputJsonValue } : {}) },
    create: { userId, enabled, meetUrl, hours: (hours ?? []) as unknown as Prisma.InputJsonValue },
  });
  return getDemoHours(userId);
}

export async function addDemoBlock(userId: string, input: { startsAt: Date; endsAt: Date; note?: string | null }) {
  if (input.endsAt <= input.startsAt) throw new BadRequestError('The end must be after the start.', 'BLOCK_RANGE');
  if (input.endsAt.getTime() - input.startsAt.getTime() > 92 * DAY_MS) throw new BadRequestError('Block at most three months at a time.', 'BLOCK_RANGE');
  await prismaUnscoped.crmDemoBlock.create({ data: { userId, startsAt: input.startsAt, endsAt: input.endsAt, note: input.note?.trim() || null } });
  return getDemoHours(userId);
}

export async function removeDemoBlock(userId: string, id: string) {
  const r = await prismaUnscoped.crmDemoBlock.deleteMany({ where: { id, userId } });
  if (!r.count) throw new NotFoundError('Blocked time not found');
  return getDemoHours(userId);
}

// ── Free slots ─────────────────────────────────────────────────────────────

interface Host {
  id: string;
  name: string;
  email: string;
  meetUrl: string;
  hours: HoursRange[];
}

/** Members taking demos now: switched on, with a Meet link, not deactivated, not on leave. */
async function demoHosts(s: CrmSettings, only?: string): Promise<Host[]> {
  const rows = await prismaUnscoped.crmDemoHost.findMany({
    where: { enabled: true, meetUrl: { not: null }, ...(only ? { userId: only } : {}), user: { deactivatedAt: null, role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] } } },
    include: { user: { select: { id: true, name: true, email: true } } },
  });
  return rows
    .filter((r) => !(s.leadOwnerOnLeave && r.userId === s.leadOwnerId))
    .map((r) => ({ id: r.userId, name: r.user.name, email: r.user.email, meetUrl: r.meetUrl!, hours: cleanHours(r.hours) }));
}

export interface Slot {
  start: Date;
  hostIds: string[];
}

/**
 * Every slot start in [from, to] that some host has free: inside their
 * hours, clear of their blocked time and of their other demos, on a day
 * they are under the cap. `ignoreDemoId` is a demo being moved.
 */
async function freeSlots(p: { from: Date; to: Date; s: CrmSettings; hostId?: string; ignoreDemoId?: string }): Promise<{ slots: Slot[]; hosts: Host[]; perDay: Map<string, number> }> {
  const hosts = await demoHosts(p.s, p.hostId);
  const minutes = p.s.demoMinutes;
  const slotMs = minutes * 60_000;
  if (!hosts.length || p.to < p.from) return { slots: [], hosts, perDay: new Map() };
  const firstDay = istDate(p.from);
  const lastDay = istDate(p.to);
  const ids = hosts.map((h) => h.id);
  const [blocks, demos] = await Promise.all([
    prismaUnscoped.crmDemoBlock.findMany({ where: { userId: { in: ids }, endsAt: { gt: p.from }, startsAt: { lt: new Date(p.to.getTime() + slotMs) } } }),
    prismaUnscoped.crmDemo.findMany({
      where: { hostId: { in: ids }, status: { not: CrmDemoStatus.CANCELLED }, startsAt: { gte: atIst(firstDay, '00:00'), lt: atIst(addDays(lastDay, 1), '00:00') }, ...(p.ignoreDemoId ? { NOT: { id: p.ignoreDemoId } } : {}) },
      select: { hostId: true, startsAt: true, endsAt: true, status: true },
    }),
  ]);
  // Demos per host per India day, for the cap.
  const perDay = new Map<string, number>();
  for (const d of demos) perDay.set(`${d.hostId}|${istDate(d.startsAt)}`, (perDay.get(`${d.hostId}|${istDate(d.startsAt)}`) ?? 0) + 1);
  const busy = (hostId: string, a: number, b: number) =>
    blocks.some((x) => x.userId === hostId && x.startsAt.getTime() < b && x.endsAt.getTime() > a) ||
    demos.some((x) => x.hostId === hostId && x.status === CrmDemoStatus.BOOKED && x.startsAt.getTime() < b && x.endsAt.getTime() > a);

  const map = new Map<number, string[]>();
  for (let date = firstDay; date <= lastDay; date = addDays(date, 1)) {
    const weekday = istWeekday(date);
    for (const h of hosts) {
      if ((perDay.get(`${h.id}|${date}`) ?? 0) >= p.s.demoDailyCap) continue;
      for (const r of h.hours.filter((x) => x.day === weekday)) {
        const end = atIst(date, r.end).getTime();
        for (let t = atIst(date, r.start).getTime(); t + slotMs <= end; t += slotMs) {
          if (t < p.from.getTime() || t > p.to.getTime()) continue;
          if (busy(h.id, t, t + slotMs)) continue;
          map.set(t, [...(map.get(t) ?? []), h.id]);
        }
      }
    }
  }
  const slots = [...map.entries()].sort((a, b) => a[0] - b[0]).map(([t, hostIds]) => ({ start: new Date(t), hostIds }));
  return { slots, hosts, perDay };
}

/** The website's slot list: from the notice period to the days-ahead limit, by India date. */
export async function publicSlots(now = new Date()) {
  const s = await getCrmSettings();
  const from = new Date(now.getTime() + s.demoNoticeMinutes * 60_000);
  const to = atIst(addDays(istDate(now), s.demoDaysAhead), '23:59');
  const { slots } = await freeSlots({ from, to, s });
  return { timezone: 'Asia/Kolkata', minutes: s.demoMinutes, days: groupByDay(slots.map((x) => x.start)) };
}

/** The CRM's slot list for booking during a call: from now, with who is free. */
export async function crmSlots(opts: { hostId?: string; days?: number }, now = new Date()) {
  const s = await getCrmSettings();
  const from = new Date(now.getTime() + 5 * 60_000);
  const to = atIst(addDays(istDate(now), Math.min(opts.days ?? s.demoDaysAhead, 31)), '23:59');
  const { slots, hosts } = await freeSlots({ from, to, s, hostId: opts.hostId });
  return {
    timezone: 'Asia/Kolkata',
    minutes: s.demoMinutes,
    hosts: hosts.map((h) => ({ id: h.id, name: h.name })),
    slots: slots.map((x) => ({ start: x.start, hostIds: x.hostIds })),
  };
}

function groupByDay(starts: Date[]) {
  const days: { date: string; slots: string[] }[] = [];
  for (const d of starts) {
    const date = istDate(d);
    const last = days[days.length - 1];
    if (last?.date === date) last.slots.push(d.toISOString());
    else days.push({ date, slots: [d.toISOString()] });
  }
  return days;
}

// ── Booking ────────────────────────────────────────────────────────────────

const hashToken = (t: string) => createHash('sha256').update(t).digest('hex');
/**
 * The owner's private link token, derived from the demo id and a server
 * secret: every message carries the same working link, and the table keeps
 * only its hash.
 */
const tokenFor = (demoId: string) => createHmac('sha256', `${env.JWT_REFRESH_SECRET}:demo-link`).update(demoId).digest('base64url');
const slotKeyOf = (hostId: string, start: Date) => `${hostId}|${start.toISOString()}`;
const manageUrl = (token: string) => `${publicSiteUrl}/book-demo/manage/?t=${encodeURIComponent(token)}`;
const bookUrl = () => `${publicSiteUrl}/book-demo/`;
const trialUrl = (type?: CrmPropertyType | null) => `${publicWebUrl}/start-trial?utm_source=demo${type === CrmPropertyType.DORMITORY ? '&type=dormitory' : ''}`;

type DemoRow = Prisma.CrmDemoGetPayload<{ include: { host: { select: { id: true; name: true; email: true } } } }>;
const withHost = { host: { select: { id: true, name: true, email: true } } } as const;

/** What the owner's booking and manage pages show. Never the host's email. */
export function publicView(d: DemoRow, now = new Date()) {
  return {
    ref: demoRef(d.number),
    status: d.status,
    startsAt: d.startsAt,
    endsAt: d.endsAt,
    when: fmtWhen(d.startsAt),
    minutes: Math.round((d.endsAt.getTime() - d.startsAt.getTime()) / 60_000),
    meetUrl: d.status === CrmDemoStatus.BOOKED ? d.meetUrl : null,
    hostName: d.host?.name.split(/\s+/)[0] ?? null,
    name: d.name,
    hostelName: d.hostelName,
    language: d.language,
    canChange: d.status === CrmDemoStatus.BOOKED && d.startsAt.getTime() > now.getTime() && d.reschedules < MAX_OWNER_MOVES,
    canCancel: d.status === CrmDemoStatus.BOOKED && d.startsAt.getTime() > now.getTime(),
  };
}

/** What the CRM shows about a demo. */
export function crmView(d: DemoRow & { contact?: { id: string; firstName: string; lastName: string | null; companyName: string | null } | null }) {
  return {
    id: d.id,
    ref: demoRef(d.number),
    status: d.status,
    startsAt: d.startsAt,
    endsAt: d.endsAt,
    host: d.host ? { id: d.host.id, name: d.host.name } : null,
    meetUrl: d.meetUrl,
    language: d.language,
    name: d.name,
    phone: d.phone,
    email: d.email,
    hostelName: d.hostelName,
    contactId: d.contactId,
    contact: d.contact ? { id: d.contact.id, name: fullName(d.contact), companyName: d.contact.companyName } : null,
    dealId: d.dealId,
    bookedVia: d.bookedVia,
    reschedules: d.reschedules,
    cancelReason: d.cancelReason,
    outcomeAt: d.outcomeAt,
    createdAt: d.createdAt,
  };
}

export interface BookInput {
  slot: Date;
  language: CrmDemoLanguage;
  /** From the website: the owner's answers. */
  lead?: Omit<LeadInput, 'source' | 'via' | 'quiet'>;
  /** From the CRM: an existing contact. */
  contactId?: string;
  hostId?: string;
  consent?: boolean;
}

/** Pick a free host for a slot: the one asked for, the lead owner, the contact's owner, then whoever has fewest that day. */
function pickHosts(slot: Slot, perDay: Map<string, number>, prefer: (string | null | undefined)[]) {
  const date = istDate(slot.start);
  const order = [...slot.hostIds].sort((a, b) => (perDay.get(`${a}|${date}`) ?? 0) - (perDay.get(`${b}|${date}`) ?? 0));
  const first = prefer.filter((x): x is string => !!x && slot.hostIds.includes(x));
  return [...new Set([...first, ...order])];
}

/** Claim the slot for one host, re-checking under a per-host lock. */
async function claimSlot(hostId: string, start: Date, end: Date, s: CrmSettings, ignoreId: string | undefined, write: (tx: Prisma.TransactionClient) => Promise<string | null>) {
  try {
    return await prismaUnscoped.$transaction(async (tx) => {
      await tx.$executeRaw`SELECT pg_advisory_xact_lock(7300003, hashtext(${hostId}))`;
      const date = istDate(start);
      const sameDay = await tx.crmDemo.findMany({
        where: { hostId, status: { not: CrmDemoStatus.CANCELLED }, startsAt: { gte: atIst(date, '00:00'), lt: atIst(addDays(date, 1), '00:00') }, ...(ignoreId ? { NOT: { id: ignoreId } } : {}) },
        select: { startsAt: true, endsAt: true, status: true },
      });
      if (sameDay.length >= s.demoDailyCap) return null;
      if (sameDay.some((x) => x.status === CrmDemoStatus.BOOKED && x.startsAt < end && x.endsAt > start)) return null;
      return write(tx);
    });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return null;
    throw e;
  }
}

const TAKEN = 'That time was just taken. Please pick another.';

/** Book a demo, from the website (lead answers) or the CRM (a contact). */
export async function bookDemo(input: BookInput, by: { via: 'website' | 'crm'; actor?: Actor }, now = new Date()) {
  const s = await getCrmSettings();
  const start = new Date(input.slot);
  if (Number.isNaN(start.getTime())) throw new BadRequestError('Pick a time.', 'INVALID_SLOT');
  if (by.via === 'website' && start.getTime() < now.getTime() + s.demoNoticeMinutes * 60_000) throw new ConflictError(TAKEN, 'SLOT_TAKEN');
  if (by.via === 'crm' && start.getTime() < now.getTime()) throw new BadRequestError('That time has passed.', 'INVALID_SLOT');

  const { slots, hosts, perDay } = await freeSlots({ from: start, to: start, s, hostId: input.hostId });
  const slot = slots.find((x) => x.start.getTime() === start.getTime());
  if (!slot) throw new ConflictError(TAKEN, 'SLOT_TAKEN');

  // Who the demo is with.
  let contactId: string;
  if (input.contactId) {
    const c = await prismaUnscoped.crmContact.findFirst({ where: { id: input.contactId, deletedAt: null }, select: { id: true } });
    if (!c) throw new BadRequestError('That contact does not exist or is in the bin.', 'INVALID_CONTACT');
    contactId = c.id;
  } else if (input.lead) {
    const r = await ingestLead({ ...input.lead, source: 'Demo booking', via: 'Website demo booking', quiet: true }, now);
    contactId = r.contactId;
  } else throw new BadRequestError('Say who the demo is with.');
  const contact = await prismaUnscoped.crmContact.findUniqueOrThrow({ where: { id: contactId } });

  const end = new Date(start.getTime() + s.demoMinutes * 60_000);
  const name = input.lead?.name?.trim() || fullName(contact);
  let demoId: string | null = null;
  let host: Host | undefined;
  for (const hid of pickHosts(slot, perDay, [input.hostId, s.leadOwnerOnLeave ? null : s.leadOwnerId, contact.ownerId])) {
    host = hosts.find((h) => h.id === hid)!;
    demoId = await claimSlot(hid, start, end, s, undefined, async (tx) => {
      const id = randomUUID();
      const d = await tx.crmDemo.create({
        data: {
          id,
          contactId,
          hostId: hid,
          startsAt: start,
          endsAt: end,
          slotKey: slotKeyOf(hid, start),
          language: input.language,
          meetUrl: host!.meetUrl,
          name,
          phone: input.lead?.phone?.trim() || contact.phone,
          email: input.lead?.email?.trim() || contact.email,
          hostelName: input.lead?.hostelName?.trim() || contact.companyName,
          tokenHash: hashToken(tokenFor(id)),
          bookedVia: by.via,
          bookedById: by.actor?.id ?? null,
          bookedAt: now,
        },
      });
      return d.id;
    });
    if (demoId) break;
  }
  if (!demoId || !host) throw new ConflictError(TAKEN, 'SLOT_TAKEN');

  const dealId = await dealForDemo(contactId, demoId, host, start, by.actor);
  const demo = await prismaUnscoped.crmDemo.findUniqueOrThrow({ where: { id: demoId }, include: withHost });
  await logDemo(demo, 'booked', by.actor, { via: by.via });
  await markTouched(contactId, now);
  if (input.consent && !contact.consentWhatsapp) {
    await prismaUnscoped.crmContact.update({ where: { id: contactId }, data: { consentWhatsapp: true, consentAt: now, consentSource: 'Website demo booking' } });
  }
  await tellOwner(demo, 'CONFIRMED');
  await tellHost(demo, 'booked', by.actor, now);
  return { demo, token: tokenFor(demo.id), dealId };
}

/** The deal a demo belongs to: the contact's open one, moved up to "Demo scheduled", or a new one there. */
async function dealForDemo(contactId: string, demoId: string, host: Host, start: Date, actor?: Actor) {
  await ensureStages();
  const stage = await demoStage(STAGE_KEYS.DEMO_SCHEDULED);
  const contact = await prismaUnscoped.crmContact.findUniqueOrThrow({ where: { id: contactId } });
  const actorName = actor?.name ?? 'Website demo booking';
  const nextStep = `Demo on ${fmtWhen(start)}`;
  const open = await prismaUnscoped.crmDeal.findFirst({
    where: { contactId, deletedAt: null, stage: { kind: CrmStageKind.OPEN } },
    orderBy: { updatedAt: 'desc' },
    include: { stage: true },
  });
  let dealId: string;
  if (open) {
    // Forward only: a deal already past "Demo scheduled" (say, on a trial) stays put.
    const moving = !!stage && stage.id !== open.stageId && open.stage.position < stage.position;
    await prismaUnscoped.$transaction([
      prismaUnscoped.crmDeal.update({
        where: { id: open.id },
        data: {
          nextStep,
          nextActionAt: start,
          ...(open.assigneeId ? {} : { assigneeId: host.id }),
          ...(moving ? { stageId: stage!.id, stageChangedAt: new Date(), position: await endOfStage(stage!.id) } : {}),
        },
      }),
      ...(moving
        ? [prismaUnscoped.crmActivity.create({ data: { dealId: open.id, contactId, type: CrmActivityType.STAGE_CHANGED, meta: { ref: dealRef(open.number), title: open.title, from: open.stage.name, to: stage!.name }, actorId: actor?.id ?? null, actorName } })]
        : []),
    ]);
    dealId = open.id;
  } else {
    const target = stage ?? (await prismaUnscoped.crmStage.findFirstOrThrow({ where: { kind: CrmStageKind.OPEN }, orderBy: { position: 'asc' } }));
    const title = `${contact.companyName || fullName(contact)} — demo`;
    const d = await prismaUnscoped.$transaction(async (tx) => {
      const d = await tx.crmDeal.create({
        data: {
          title,
          stageId: target.id,
          position: await endOfStage(target.id),
          contactId,
          assigneeId: host.id,
          companyName: contact.companyName,
          source: 'Demo booking',
          beds: contact.approxBeds,
          value: contact.approxBeds ? contact.approxBeds * BED_PRICE_YEAR : 0,
          nextStep,
          nextActionAt: start,
          createdById: actor?.id ?? null,
          updatedById: actor?.id ?? null,
        },
      });
      await tx.crmActivity.create({ data: { dealId: d.id, contactId, type: CrmActivityType.CREATED, meta: { ref: dealRef(d.number), title: d.title }, actorId: actor?.id ?? null, actorName } });
      return d;
    });
    dealId = d.id;
  }
  await prismaUnscoped.crmDemo.update({ where: { id: demoId }, data: { dealId } });
  return dealId;
}

async function endOfStage(stageId: string) {
  const top = await prismaUnscoped.crmDeal.aggregate({ where: { stageId, deletedAt: null }, _max: { position: true } });
  return (top._max.position ?? 0) + 1;
}

/** One line on the contact's (and deal's) timeline. */
async function logDemo(d: DemoRow, event: 'booked' | 'moved' | 'cancelled' | 'done' | 'no_show', actor: Actor | undefined, extra: Record<string, unknown> = {}, body?: string | null) {
  await prismaUnscoped.crmActivity.create({
    data: {
      contactId: d.contactId,
      dealId: d.dealId,
      type: CrmActivityType.DEMO,
      body: body?.slice(0, 2000) ?? null,
      meta: { event, ref: demoRef(d.number), startsAt: d.startsAt.toISOString(), host: d.host?.name ?? null, language: d.language, ...extra } as Prisma.InputJsonValue,
      actorId: actor?.id ?? null,
      actorName: actor?.name ?? (event === 'booked' ? 'Website demo booking' : 'The owner, from their booking link'),
    },
  });
}

// ── Messages ───────────────────────────────────────────────────────────────

function ics(d: DemoRow, cancelled = false) {
  return {
    filename: 'hostelcare-demo.ics',
    content: Buffer.from(
      demoIcs({
        uid: d.id,
        start: d.startsAt,
        end: d.endsAt,
        title: 'HostelCare demo',
        description: `Your ${Math.round((d.endsAt.getTime() - d.startsAt.getTime()) / 60_000)}-minute HostelCare demo${d.host ? ` with ${d.host.name}` : ''}.${d.meetUrl ? ` Join: ${d.meetUrl}` : ''}`,
        url: d.meetUrl,
        sequence: d.reschedules + (cancelled ? 1 : 0),
        cancelled,
      }),
    ),
  };
}

export function demoIcsFile(d: DemoRow) {
  return ics(d, d.status === CrmDemoStatus.CANCELLED).content.toString();
}

/** The owner's email (and WhatsApp, once the template is approved and they agreed). */
async function tellOwner(d: DemoRow, kind: DemoOwnerEmailKind, opts: { key?: string } = {}) {
  const contact = await prismaUnscoped.crmContact.findUnique({ where: { id: d.contactId }, select: { consentWhatsapp: true, propertyType: true, optedOutAt: true } });
  // L6: after a stop, only what answers their own action (booked, moved, cancelled) still goes.
  if (contact?.optedOutAt && kind !== 'CONFIRMED' && kind !== 'MOVED' && kind !== 'CANCELLED') return;
  const when = fmtWhen(d.startsAt);
  const minutes = Math.round((d.endsAt.getTime() - d.startsAt.getTime()) / 60_000);
  const links = { manageUrl: manageUrl(tokenFor(d.id)), bookUrl: bookUrl(), trialUrl: trialUrl(contact?.propertyType) };
  if (d.email) {
    const mail = demoOwnerEmail(kind, { unsubscribeUrl: unsubscribeUrl(d.contactId), name: d.name.split(/\s+/)[0], when, minutes, hostName: d.host?.name.split(/\s+/)[0] ?? null, meetUrl: d.meetUrl, hindi: d.language === CrmDemoLanguage.HI, ...links });
    await deliver({
      key: opts.key ?? `demo:${d.id}:${kind}:${d.reschedules}`,
      kind: `DEMO_${kind}`,
      to: d.email,
      mail,
      force: true,
      ...(kind === 'CONFIRMED' || kind === 'MOVED' || kind === 'CANCELLED' ? { attachments: [ics(d, kind === 'CANCELLED')] } : {}),
    });
  }
  if (d.phone && contact?.consentWhatsapp) {
    const tpl =
      kind === 'CONFIRMED' || kind === 'MOVED' ? { name: env.WHATSAPP_TEMPLATE_DEMO_CONFIRM, params: [d.name.split(/\s+/)[0], when, d.meetUrl ?? '', links.manageUrl] } :
      kind === 'EVENING' || kind === 'HOUR' ? { name: env.WHATSAPP_TEMPLATE_DEMO_REMINDER, params: [d.name.split(/\s+/)[0], when, d.meetUrl ?? ''] } :
      kind === 'RECAP' ? { name: env.WHATSAPP_TEMPLATE_DEMO_RECAP, params: [d.name.split(/\s+/)[0], links.trialUrl] } :
      kind === 'NO_SHOW' ? { name: env.WHATSAPP_TEMPLATE_DEMO_NOSHOW, params: [d.name.split(/\s+/)[0], links.bookUrl] } :
      null;
    // Only an approved template reaches someone outside a chat window.
    if (tpl?.name) {
      await sendWhatsAppTemplate(d.phone, tpl.name, tpl.params, `HostelCare demo (${kind.toLowerCase()}): ${when}`, { tenantId: null, purpose: 'DEMO' });
    }
  }
}

const HOST_WORD = { booked: 'Demo booked', moved: 'Demo moved', cancelled: 'Demo cancelled', soon: 'Demo in 15 minutes', away: 'Demo moved to someone else' } as const;

/** The host's email (one per event); the super admin sees it in their 10-minute digest. */
async function tellHost(d: DemoRow, event: keyof typeof HOST_WORD, actor: Actor | undefined, now: Date, hostOverride?: { id: string; name: string; email: string }) {
  const host = hostOverride ?? d.host;
  if (!host || (actor && actor.id === host.id && event !== 'soon')) return;
  const url = crmUrl(`contacts/${d.contactId}`);
  const contact = await prismaUnscoped.crmContact.findUnique({ where: { id: d.contactId }, select: { approxBeds: true, propertyType: true, city: true } });
  const what = [d.hostelName, contact?.approxBeds ? `${contact.approxBeds} beds` : null, contact?.city].filter(Boolean).join(' · ');
  const title = `${HOST_WORD[event]}: ${d.name}${d.hostelName ? `, ${d.hostelName}` : ''}`;
  await deliver({
    key: `demo-host:${d.id}:${event}:${d.reschedules}:${host.id}`,
    kind: 'DEMO_HOST',
    to: host.email,
    userId: host.id,
    mail: crmEmail({
      title,
      intro:
        event === 'soon' ? `Your demo with ${d.name} starts at ${fmtWhen(d.startsAt)}.` :
        event === 'cancelled' ? `The demo on ${fmtWhen(d.startsAt)} is cancelled${d.cancelReason ? `: ${d.cancelReason}` : ''}.` :
        event === 'away' ? `The demo on ${fmtWhen(d.startsAt)} has moved to another time or host. Nothing to do.` :
        `${d.name} ${event === 'moved' ? 'moved their demo to' : 'booked a demo for'} ${fmtWhen(d.startsAt)}${d.language === CrmDemoLanguage.HI ? ', in Hindi' : ''}.`,
      badge: event === 'soon' ? 'Starting soon' : event === 'cancelled' ? 'Cancelled' : 'Demo',
      tone: event === 'cancelled' ? 'warning' : 'info',
      figures: [
        ['When', fmtWhen(d.startsAt)],
        ['Language', d.language === CrmDemoLanguage.HI ? 'Hindi' : 'English'],
      ],
      sections: [
        {
          heading: 'With',
          items: [
            { text: d.name, sub: what || undefined, url },
            ...(d.phone ? [{ text: d.phone, sub: 'Phone' }] : []),
            ...(d.email ? [{ text: d.email, sub: 'Email' }] : []),
          ],
        },
      ],
      cta: event === 'soon' && d.meetUrl ? { label: 'Join on Google Meet', url: d.meetUrl } : { label: 'Open the contact', url },
      reason: 'You take HostelCare demos. Change your demo hours in the CRM under Demos.',
    }),
  });
  if (event === 'booked' || event === 'cancelled') {
    const copy = await superAdminCopyAddress({ recipients: [host.email] });
    if (copy) await queueReminderCopy(copy, { text: `${title} → ${host.name}`, url }, now);
  }
}

// ── Owner's link: view, move, cancel ───────────────────────────────────────

async function byToken(token: string) {
  const d = await prismaUnscoped.crmDemo.findUnique({ where: { tokenHash: hashToken(token) }, include: withHost });
  if (!d) throw new NotFoundError('This link is not valid any more. Use the newest email about your demo, or book again.', 'DEMO_LINK_INVALID');
  return d;
}

export async function viewByToken(token: string, now = new Date()) {
  return publicView(await byToken(token), now);
}

export async function icsByToken(token: string) {
  return demoIcsFile(await byToken(token));
}

/** Move a booked demo to another free slot (by the owner's link, or by sales). */
export async function rescheduleDemo(d: DemoRow, slotIso: string | Date, by: { actor?: Actor; hostId?: string }, now = new Date()) {
  if (d.status !== CrmDemoStatus.BOOKED) throw new BadRequestError('Only a booked demo can be moved.', 'DEMO_NOT_BOOKED');
  if (!by.actor && d.reschedules >= MAX_OWNER_MOVES) throw new TooManyRequestsError('This demo has been moved too many times. Please book a new one.', 'DEMO_MOVE_LIMIT');
  const s = await getCrmSettings();
  const start = new Date(slotIso);
  if (Number.isNaN(start.getTime())) throw new BadRequestError('Pick a time.', 'INVALID_SLOT');
  const notice = by.actor ? 5 : s.demoNoticeMinutes;
  if (start.getTime() < now.getTime() + notice * 60_000) throw new ConflictError(TAKEN, 'SLOT_TAKEN');
  const { slots, hosts, perDay } = await freeSlots({ from: start, to: start, s, hostId: by.hostId, ignoreDemoId: d.id });
  const slot = slots.find((x) => x.start.getTime() === start.getTime());
  if (!slot) throw new ConflictError(TAKEN, 'SLOT_TAKEN');
  const end = new Date(start.getTime() + s.demoMinutes * 60_000);
  const oldHost = d.host;
  let moved: string | null = null;
  for (const hid of pickHosts(slot, perDay, [by.hostId, d.hostId])) {
    const host = hosts.find((h) => h.id === hid)!;
    moved = await claimSlot(hid, start, end, s, d.id, async (tx) => {
      const r = await tx.crmDemo.updateMany({
        where: { id: d.id, status: CrmDemoStatus.BOOKED },
        data: { hostId: hid, startsAt: start, endsAt: end, slotKey: slotKeyOf(hid, start), meetUrl: host.meetUrl, bookedAt: now, reschedules: { increment: 1 }, remindedEveningAt: null, remindedHourAt: null, hostRemindedAt: null },
      });
      return r.count ? d.id : null;
    });
    if (moved) break;
  }
  if (!moved) throw new ConflictError(TAKEN, 'SLOT_TAKEN');
  const fresh = await prismaUnscoped.crmDemo.findUniqueOrThrow({ where: { id: d.id }, include: withHost });
  await logDemo(fresh, 'moved', by.actor, { from: d.startsAt.toISOString() });
  if (fresh.dealId) await prismaUnscoped.crmDeal.update({ where: { id: fresh.dealId }, data: { nextStep: `Demo on ${fmtWhen(start)}`, nextActionAt: start } });
  await tellOwner(fresh, 'MOVED');
  await tellHost(fresh, 'moved', by.actor, now);
  if (oldHost && oldHost.id !== fresh.hostId) await tellHost(fresh, 'away', by.actor, now, oldHost);
  return fresh;
}

export async function cancelDemo(d: DemoRow, reason: string | null, by: { actor?: Actor }, now = new Date()) {
  if (d.status !== CrmDemoStatus.BOOKED) throw new BadRequestError('Only a booked demo can be cancelled.', 'DEMO_NOT_BOOKED');
  const r = await prismaUnscoped.crmDemo.updateMany({ where: { id: d.id, status: CrmDemoStatus.BOOKED }, data: { status: CrmDemoStatus.CANCELLED, slotKey: null, cancelReason: reason?.trim() || null, outcomeAt: now, outcomeById: by.actor?.id ?? null } });
  if (!r.count) throw new BadRequestError('Only a booked demo can be cancelled.', 'DEMO_NOT_BOOKED');
  const fresh = await prismaUnscoped.crmDemo.findUniqueOrThrow({ where: { id: d.id }, include: withHost });
  await logDemo(fresh, 'cancelled', by.actor, {}, fresh.cancelReason);
  if (fresh.dealId) await prismaUnscoped.crmDeal.update({ where: { id: fresh.dealId }, data: { nextStep: 'Demo cancelled — call to book another', nextActionAt: now } });
  await tellOwner(fresh, 'CANCELLED');
  await tellHost(fresh, 'cancelled', by.actor, now);
  return fresh;
}

export async function rescheduleByToken(token: string, slot: string, now = new Date()) {
  return publicView(await rescheduleDemo(await byToken(token), slot, {}, now), now);
}

export async function cancelByToken(token: string, reason: string | null, now = new Date()) {
  return publicView(await cancelDemo(await byToken(token), reason, {}, now), now);
}

// ── The CRM side ───────────────────────────────────────────────────────────

async function loadDemo(id: string) {
  const d = await prismaUnscoped.crmDemo.findUnique({ where: { id }, include: withHost });
  if (!d) throw new NotFoundError('Demo not found');
  return d;
}

const listInclude = { ...withHost, contact: { select: { id: true, firstName: true, lastName: true, companyName: true } } } as const;

export async function listDemos(q: { from?: Date; to?: Date; hostId?: string; contactId?: string; status?: CrmDemoStatus }, limit = 100) {
  const rows = await prismaUnscoped.crmDemo.findMany({
    where: {
      ...(q.from || q.to ? { startsAt: { ...(q.from ? { gte: q.from } : {}), ...(q.to ? { lt: q.to } : {}) } } : {}),
      ...(q.hostId ? { hostId: q.hostId } : {}),
      ...(q.contactId ? { contactId: q.contactId } : {}),
      ...(q.status ? { status: q.status } : {}),
    },
    orderBy: { startsAt: q.to && !q.from ? 'desc' : 'asc' },
    take: Math.min(limit, 200),
    include: listInclude,
  });
  return rows.map(crmView);
}

export async function getDemo(id: string) {
  const d = await prismaUnscoped.crmDemo.findUnique({ where: { id }, include: listInclude });
  if (!d) throw new NotFoundError('Demo not found');
  return crmView(d);
}

export async function bookFromCrm(input: { contactId: string; slot: string; hostId?: string; language: CrmDemoLanguage }, actor: Actor) {
  const r = await bookDemo({ contactId: input.contactId, slot: new Date(input.slot), hostId: input.hostId, language: input.language }, { via: 'crm', actor });
  return getDemo(r.demo.id);
}

export async function moveFromCrm(id: string, slot: string, hostId: string | undefined, actor: Actor) {
  await rescheduleDemo(await loadDemo(id), slot, { actor, hostId });
  return getDemo(id);
}

export async function cancelFromCrm(id: string, reason: string | null, actor: Actor) {
  await cancelDemo(await loadDemo(id), reason, { actor });
  return getDemo(id);
}

/** An outcome can be recorded from 15 minutes before the start. */
function assertStarted(d: DemoRow, now: Date) {
  if (d.status !== CrmDemoStatus.BOOKED) throw new BadRequestError('This demo already has an outcome.', 'DEMO_NOT_BOOKED');
  if (d.startsAt.getTime() - 15 * 60_000 > now.getTime()) throw new BadRequestError(`This demo is on ${fmtWhen(d.startsAt)}; record how it went after it starts.`, 'DEMO_NOT_STARTED');
}

/** The demo happened: the deal moves to "Demo done" and the owner gets the trial link. */
export async function markDemoDone(id: string, note: string | null, actor: Actor, now = new Date()) {
  const d = await loadDemo(id);
  assertStarted(d, now);
  const r = await prismaUnscoped.crmDemo.updateMany({ where: { id, status: CrmDemoStatus.BOOKED }, data: { status: CrmDemoStatus.DONE, slotKey: null, outcomeAt: now, outcomeById: actor.id } });
  if (!r.count) throw new BadRequestError('This demo already has an outcome.', 'DEMO_NOT_BOOKED');
  const fresh = await loadDemo(id);
  await logDemo(fresh, 'done', actor, {}, note);
  if (fresh.dealId) {
    const deal = await prismaUnscoped.crmDeal.findFirst({ where: { id: fresh.dealId, deletedAt: null }, include: { stage: true } });
    const done = await demoStage(STAGE_KEYS.DEMO_DONE);
    if (deal && done && deal.stage.kind === CrmStageKind.OPEN && deal.stage.position < done.position) await moveDeal(deal.id, { stageId: done.id }, actor);
    if (deal) await prismaUnscoped.crmDeal.update({ where: { id: deal.id }, data: { nextStep: 'Follow up: start their free trial', nextActionAt: new Date(now.getTime() + DAY_MS) } });
  }
  await prismaUnscoped.crmContact.updateMany({ where: { id: fresh.contactId, status: CrmContactStatus.NEW }, data: { status: CrmContactStatus.CONTACTED, lastContactedAt: now } });
  await tellOwner(fresh, 'RECAP');
  return getDemo(id);
}

/** They did not come: "sorry we missed you"; a second miss sends them to Nurture and loses the deal. */
export async function markDemoNoShow(id: string, actor: Actor, now = new Date()) {
  const d = await loadDemo(id);
  assertStarted(d, now);
  const r = await prismaUnscoped.crmDemo.updateMany({ where: { id, status: CrmDemoStatus.BOOKED }, data: { status: CrmDemoStatus.NO_SHOW, slotKey: null, outcomeAt: now, outcomeById: actor.id } });
  if (!r.count) throw new BadRequestError('This demo already has an outcome.', 'DEMO_NOT_BOOKED');
  const fresh = await loadDemo(id);
  const misses = await prismaUnscoped.crmDemo.count({ where: { contactId: fresh.contactId, status: CrmDemoStatus.NO_SHOW } });
  const nurture = misses >= 2;
  await logDemo(fresh, 'no_show', actor, { misses, ...(nurture ? { nurture: true } : {}) });
  await tellOwner(fresh, 'NO_SHOW');
  if (nurture) {
    await addToNurture(fresh.contactId, actor);
    const lost = await prismaUnscoped.crmStage.findFirst({ where: { kind: CrmStageKind.LOST } });
    if (fresh.dealId && lost) {
      const deal = await prismaUnscoped.crmDeal.findFirst({ where: { id: fresh.dealId, deletedAt: null }, include: { stage: true } });
      if (deal && deal.stage.kind === CrmStageKind.OPEN) await moveDeal(deal.id, { stageId: lost.id, lostReasonCode: 'MISSED_DEMOS' }, actor);
    }
  } else if (fresh.dealId) {
    await prismaUnscoped.crmDeal.update({ where: { id: fresh.dealId }, data: { nextStep: 'Missed the demo — call to book another', nextActionAt: now } });
  }
  return { demo: await getDemo(id), nurtured: nurture };
}

// ── Reminders (the CRM clock) ──────────────────────────────────────────────

/**
 * Owner: the evening before at 6 pm (if booked before then) and an hour
 * before (if booked more than an hour ahead). Host: 15 minutes before.
 * Each is claimed before it is sent, so a second clock never repeats it.
 */
export async function demoReminders(now = new Date()): Promise<number> {
  const soon = await prismaUnscoped.crmDemo.findMany({
    where: { status: CrmDemoStatus.BOOKED, startsAt: { gt: now, lt: new Date(now.getTime() + 2 * DAY_MS) } },
    include: withHost,
    take: 500,
  });
  let sent = 0;
  for (const d of soon) {
    const start = d.startsAt.getTime();
    const evening = atIst(addDays(istDate(d.startsAt), -1), '18:00').getTime();
    if (!d.remindedEveningAt && now.getTime() >= evening && start - now.getTime() > 60 * 60_000 && d.bookedAt.getTime() < evening) {
      if (await claim(d.id, 'remindedEveningAt', now)) {
        await tellOwner(d, 'EVENING', { key: `demo:${d.id}:EVENING:${d.reschedules}` });
        sent++;
      }
    }
    if (!d.remindedHourAt && start - now.getTime() <= 60 * 60_000 && start - d.bookedAt.getTime() > 60 * 60_000) {
      if (await claim(d.id, 'remindedHourAt', now)) {
        await tellOwner(d, 'HOUR', { key: `demo:${d.id}:HOUR:${d.reschedules}` });
        sent++;
      }
    }
    if (!d.hostRemindedAt && start - now.getTime() <= 15 * 60_000) {
      if (await claim(d.id, 'hostRemindedAt', now)) {
        await tellHost(d, 'soon', undefined, now);
        sent++;
      }
    }
  }
  return sent;
}

async function claim(id: string, field: 'remindedEveningAt' | 'remindedHourAt' | 'hostRemindedAt', now: Date) {
  const r = await prismaUnscoped.crmDemo.updateMany({ where: { id, status: CrmDemoStatus.BOOKED, [field]: null }, data: { [field]: now } });
  return r.count === 1;
}
