import { CrmActivityType, CrmContactStatus, CrmLeadGrade, CrmPropertyType, Prisma, Role } from '@prisma/client';
import { env, publicSiteUrl, publicWebUrl } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { crmEmail, leadTouchEmail } from '../../lib/email-templates';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { getCrmSettings, superAdminCopyAddress, type CrmSettings } from './crm-settings.service';
import { crmUrl, deliver, fmtIst, fmtIstTime } from './crm-mail';
import { queueReminderCopy } from './crm-notify';
import { fullName, phoneKeyOf, unsubscribeUrl } from './crm-contacts.service';
import { stageByKey, STAGE_KEYS } from './crm-stages.service';

/**
 * Inbound leads (Sprint L1, 20 Oct 2026): every enquiry lands in the CRM by
 * itself, graded, owned, and on a first-response clock.
 *
 * - One person, one record: a returning phone or email updates the contact
 *   it already has (and brings it back from the bin) instead of a second one.
 *   `source` stays where they first came from; `latestSource` is the last.
 * - Graded from what they told us: HOT (hostel or dormitory with the hot-bed
 *   count or more), WARM, PG (not sold yet), NOT_A_FIT (e.g. a student
 *   looking for a room — closed as Lost, no alert).
 * - Owned by the lead owner in CRM settings, or the super admin while that
 *   person is on leave or none is set.
 * - On a clock: `leadDueAt` is the response time in working hours (India
 *   time). The owner is alerted at once by email (and WhatsApp once Meta has
 *   approved the template); the first real contact sets `firstTouchAt`; a
 *   lead still untouched when the clock runs out is reported to the super
 *   admin by the 5-minute CRM tick, all late leads in one email.
 */

/** Sources the automation writes. The settings list holds these and the team's own. */
export const LEAD_SOURCES = ['Website', 'Demo booking', 'Trial signup', 'Meta ads', 'WhatsApp', 'Referral', 'Cold call', 'Social DM', 'Event', 'Partner'] as const;

const IST_MS = 330 * 60_000;
const MIN = 60_000;
const DAY = 86_400_000;
const minutesOf = (hm: string) => {
  const [h, m] = hm.split(':').map(Number);
  return h * 60 + m;
};

type Clock = Pick<CrmSettings, 'workDays' | 'workStart' | 'workEnd' | 'responseMinutes'>;

/**
 * When a lead that arrived at `from` must be contacted by: `responseMinutes`
 * of working time later, counting only working days and hours in India time.
 * A lead after hours is due that many minutes after the next opening.
 */
export function workingDue(from: Date, s: Clock): Date {
  const start = minutesOf(s.workStart);
  const end = minutesOf(s.workEnd);
  const days = new Set(s.workDays);
  if (!days.size || end <= start) return new Date(from.getTime() + s.responseMinutes * MIN);
  let left = s.responseMinutes;
  // Shifted by India's offset, so the UTC getters read India's clock.
  let t = from.getTime() + IST_MS;
  for (let guard = 0; guard < 400; guard++) {
    const d = new Date(t);
    const dayStart = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
    const minute = (t - dayStart) / MIN;
    if (!days.has(d.getUTCDay()) || minute >= end) {
      t = dayStart + DAY + start * MIN;
      continue;
    }
    if (minute < start) t = dayStart + start * MIN;
    const room = end - (t - dayStart) / MIN;
    if (left <= room) return new Date(t + left * MIN - IST_MS);
    left -= room;
    t = dayStart + DAY + start * MIN;
  }
  return new Date(from.getTime() + s.responseMinutes * MIN);
}

const PLACES: (CrmPropertyType | null | undefined)[] = [CrmPropertyType.HOSTEL, CrmPropertyType.DORMITORY, CrmPropertyType.UNIVERSITY, CrmPropertyType.COLIVING, null, undefined];

export function gradeOf(type: CrmPropertyType | null | undefined, beds: number | null | undefined, hotBeds: number, notFit = false): CrmLeadGrade {
  if (notFit) return CrmLeadGrade.NOT_A_FIT;
  if (type === CrmPropertyType.PG) return CrmLeadGrade.PG;
  if (PLACES.includes(type) && (beds ?? 0) >= hotBeds) return CrmLeadGrade.HOT;
  return CrmLeadGrade.WARM;
}

const GRADE_WORD: Record<CrmLeadGrade, string> = { HOT: 'Hot', WARM: 'New', PG: 'PG', NOT_A_FIT: 'Not a fit' };
const TYPE_WORD: Partial<Record<CrmPropertyType, string>> = { HOSTEL: 'hostel', DORMITORY: 'dormitory', PG: 'PG', UNIVERSITY: 'university hostel', COLIVING: 'co-living' };

const personSelect = { id: true, name: true, email: true, phone: true } as const;
type Person = { id: string; name: string; email: string; phone: string | null };

async function superAdmin(): Promise<Person | null> {
  return prismaUnscoped.user.findFirst({ where: { role: Role.SUPER_ADMIN, deactivatedAt: null }, orderBy: { createdAt: 'asc' }, select: personSelect });
}

async function activeMember(id: string | null | undefined): Promise<Person | null> {
  if (!id) return null;
  return prismaUnscoped.user.findFirst({ where: { id, deactivatedAt: null, role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] } }, select: personSelect });
}

/** Who owns new leads right now: the lead owner, or the super admin while they are away. */
export async function leadOwner(s: CrmSettings): Promise<Person | null> {
  if (!s.leadOwnerOnLeave) {
    const owner = await activeMember(s.leadOwnerId);
    if (owner) return owner;
  }
  return superAdmin();
}

export interface LeadInput {
  name: string;
  phone?: string | null;
  email?: string | null;
  hostelName?: string | null;
  type?: CrmPropertyType | null;
  beds?: number | null;
  city?: string | null;
  state?: string | null;
  message?: string | null;
  /** They said they are not a business (e.g. a student looking for a room). */
  notFit?: boolean;
  /** They ticked "contact me on WhatsApp". */
  consent?: boolean;
  /** One of LEAD_SOURCES. */
  source: string;
  /** Where exactly, in words: "Website contact form". */
  via: string;
  /** Page, campaign and the like, kept on the timeline entry. */
  meta?: Record<string, string>;
  /**
   * No new-lead alert and no first-call clock: a booked demo (L3) is its own
   * appointment, and its host is told about it separately.
   */
  quiet?: boolean;
  /**
   * The automatic first message (L4) to a brand-new lead: on unless the
   * source already answers them itself (a trial's welcome, the WhatsApp reply).
   */
  firstTouch?: boolean;
}

export interface LeadResult {
  contactId: string;
  created: boolean;
  grade: CrmLeadGrade;
  ownerId: string | null;
  dueAt: Date | null;
}

const emailKeyOf = (e: string | null | undefined) => (e && e.trim() ? e.trim().toLowerCase() : null);
const blank = (v: string | null | undefined) => !v || !v.trim();

/** Take one enquiry into the CRM. Never throws on a duplicate: it merges. */
export async function ingestLead(input: LeadInput, now = new Date()): Promise<LeadResult> {
  const s = await getCrmSettings();
  const pk = phoneKeyOf(input.phone);
  const ek = emailKeyOf(input.email);
  const [first, ...rest] = input.name.trim().split(/\s+/);
  const lastName = rest.join(' ') || null;
  const owner = await leadOwner(s);
  const match =
    pk || ek
      ? await prismaUnscoped.crmContact.findFirst({
          where: { OR: [...(pk ? [{ phoneKey: pk }] : []), ...(ek ? [{ emailKey: ek }] : [])] },
          // A live record beats one in the bin; the most recently touched wins.
          orderBy: [{ deletedAt: { sort: 'asc', nulls: 'first' } }, { updatedAt: 'desc' }],
        })
      : null;
  const consent = input.consent ? { consentWhatsapp: true, consentAt: now, consentSource: input.via } : {};
  const leadMeta = {
    source: input.source,
    via: input.via,
    ...(input.message ? { message: input.message.slice(0, 1000) } : {}),
    ...(input.beds ? { beds: input.beds } : {}),
    ...(input.type ? { type: input.type } : {}),
    ...(input.meta ?? {}),
  };

  if (!match) {
    const grade = gradeOf(input.type, input.beds, s.hotBeds, input.notFit);
    const live = grade !== CrmLeadGrade.NOT_A_FIT;
    const dueAt = live && !input.quiet ? workingDue(now, s) : null;
    const c = await prismaUnscoped.$transaction(async (tx) => {
      const c = await tx.crmContact.create({
        data: {
          firstName: first,
          lastName,
          email: input.email?.trim() || null,
          emailKey: ek,
          phone: input.phone?.trim() || null,
          phoneKey: pk,
          companyName: input.hostelName?.trim() || null,
          city: input.city?.trim() || null,
          state: input.state?.trim() || null,
          propertyType: input.type ?? null,
          approxBeds: input.beds ?? null,
          status: live ? CrmContactStatus.NEW : CrmContactStatus.LOST,
          source: input.source,
          latestSource: input.source,
          lastInboundAt: now,
          leadGrade: grade,
          leadDueAt: dueAt,
          // The ad campaign that brought them, for cost per lead (L6).
          firstCampaign: input.meta?.utmCampaign?.slice(0, 120) ?? null,
          ownerId: owner?.id ?? null,
          ...consent,
          createdAt: now,
        },
      });
      await tx.crmActivity.createMany({
        data: [
          { contactId: c.id, type: CrmActivityType.CREATED, actorName: input.via, createdAt: now },
          { contactId: c.id, type: CrmActivityType.LEAD_IN, body: input.message?.slice(0, 1000) ?? null, meta: { ...leadMeta, again: false } as Prisma.InputJsonValue, actorName: input.via, createdAt: new Date(now.getTime() + 1) },
        ],
      });
      return c;
    });
    // L5: every live lead is a deal at 'New lead' with the first call as its next action; PG leads wait on their list.
    if (live && !input.quiet && grade !== CrmLeadGrade.PG) await safely(() => openLeadDeal(c.id, owner?.id ?? null, input, dueAt, now));
    if (grade === CrmLeadGrade.PG) await safely(() => addToList(c.id, 'PG – later', 'PG leads: hear from us again when PG is ready.', 'slate', input.via));
    if (live && owner && !input.quiet) await alertNewLead(c, owner, input, false, now);
    if (live && !input.quiet && input.firstTouch !== false) await safely(() => sendFirstTouch(c.id, now));
    return { contactId: c.id, created: true, grade, ownerId: owner?.id ?? null, dueAt };
  }

  // They came again: fill what we did not know, never overwrite what we did.
  const type = match.propertyType ?? input.type ?? null;
  const beds = match.approxBeds ?? input.beds ?? null;
  const grade = gradeOf(type, beds, s.hotBeds, input.notFit && !match.leadGrade);
  // A lead still waiting, or one we had lost, is a fresh lead again; anyone
  // further along (contacted, qualified, a customer) just gets the note.
  const reopen = (match.status === CrmContactStatus.NEW || match.status === CrmContactStatus.LOST) && grade !== CrmLeadGrade.NOT_A_FIT;
  const dueAt = reopen ? (input.quiet ? null : workingDue(now, s)) : match.leadDueAt;
  const alertTo = (await (async () => {
    if (match.ownerId && !(s.leadOwnerOnLeave && match.ownerId === s.leadOwnerId)) return activeMember(match.ownerId);
    return null;
  })()) ?? owner;
  const data: Prisma.CrmContactUncheckedUpdateInput = {
    latestSource: input.source,
    lastInboundAt: now,
    leadGrade: grade,
    ...(blank(match.email) && ek ? { email: input.email!.trim(), emailKey: ek } : {}),
    ...(blank(match.phone) && pk ? { phone: input.phone!.trim(), phoneKey: pk } : {}),
    ...(blank(match.companyName) && !blank(input.hostelName) ? { companyName: input.hostelName!.trim() } : {}),
    ...(blank(match.city) && !blank(input.city) ? { city: input.city!.trim() } : {}),
    ...(blank(match.state) && !blank(input.state) ? { state: input.state!.trim() } : {}),
    ...(!match.propertyType && input.type ? { propertyType: input.type } : {}),
    ...(!match.approxBeds && input.beds ? { approxBeds: input.beds } : {}),
    ...(!match.consentWhatsapp ? consent : {}),
    ...(match.deletedAt ? { deletedAt: null, deletedById: null } : {}),
    ...(!match.ownerId && alertTo ? { ownerId: alertTo.id } : {}),
    ...(reopen ? { status: CrmContactStatus.NEW, leadDueAt: dueAt, firstTouchAt: null, escalatedAt: null } : {}),
  };
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.update({ where: { id: match.id }, data }),
    prismaUnscoped.crmActivity.createMany({
      data: [
        ...(match.deletedAt ? [{ contactId: match.id, type: CrmActivityType.RESTORED, actorName: input.via, createdAt: now }] : []),
        { contactId: match.id, type: CrmActivityType.LEAD_IN, body: input.message?.slice(0, 1000) ?? null, meta: { ...leadMeta, again: true } as Prisma.InputJsonValue, actorName: input.via, createdAt: new Date(now.getTime() + 1) },
      ],
    }),
  ]);
  const fresh = await prismaUnscoped.crmContact.findUniqueOrThrow({ where: { id: match.id } });
  if (alertTo && fresh.leadGrade !== CrmLeadGrade.NOT_A_FIT && !input.quiet) await alertNewLead(fresh, alertTo, input, true, now);
  return { contactId: match.id, created: false, grade: fresh.leadGrade ?? grade, ownerId: fresh.ownerId, dueAt: fresh.leadDueAt };
}

type LeadContact = Prisma.CrmContactGetPayload<object>;

/** The owner hears about a lead at once, by email and (once approved) WhatsApp. */
async function alertNewLead(c: LeadContact, to: Person, input: LeadInput, again: boolean, now: Date) {
  const name = fullName(c);
  const grade = c.leadGrade ?? CrmLeadGrade.WARM;
  const what = [c.companyName, c.approxBeds ? `${c.approxBeds} beds` : null, c.propertyType ? TYPE_WORD[c.propertyType] : null, c.city].filter(Boolean).join(' · ');
  const url = crmUrl(`contacts/${c.id}`);
  const due = c.status === CrmContactStatus.NEW ? c.leadDueAt : null;
  const title = `${again ? 'Back again' : `${GRADE_WORD[grade]} lead`}: ${name}${c.companyName ? `, ${c.companyName}` : ''}`;
  await deliver({
    key: `lead:${c.id}:${now.getTime()}`,
    kind: 'LEAD',
    to: to.email,
    userId: to.id,
    mail: crmEmail({
      title,
      intro: `${name} ${again ? 'got in touch again' : 'came in'} via ${input.via}.${due ? ` Call by ${fmtIst(due)}.` : ''}`,
      badge: grade === CrmLeadGrade.HOT ? 'Hot lead' : grade === CrmLeadGrade.PG ? 'PG lead' : 'New lead',
      tone: grade === CrmLeadGrade.HOT ? 'warning' : 'info',
      figures: [
        ...(c.approxBeds ? [['Beds', String(c.approxBeds)] as [string, string]] : []),
        ...(c.city ? [['City', c.city] as [string, string]] : []),
        ...(due ? [['Call by', fmtIstTime(due)] as [string, string]] : []),
      ],
      sections: [
        {
          heading: 'Lead',
          items: [
            { text: name, sub: what || undefined, url },
            ...(c.phone ? [{ text: c.phone, sub: c.consentWhatsapp ? 'Agreed to WhatsApp' : 'Phone' }] : []),
            ...(c.email ? [{ text: c.email, sub: 'Email' }] : []),
            ...(input.message ? [{ text: input.message.slice(0, 300), sub: 'Their message' }] : []),
          ],
        },
      ],
      cta: { label: 'Open the lead', url },
      reason: 'You receive new leads in the HostelCare CRM. The super admin changes who gets them in CRM settings.',
    }),
  });
  // The super admin sees it in their 10-minute digest, not as one more email.
  const copy = await superAdminCopyAddress({ recipients: [to.email] });
  if (copy) await queueReminderCopy(copy, { text: `${title} (${input.via}) → ${to.name}`, url }, now);
  if (env.WHATSAPP_TEMPLATE_LEAD_ALERT && to.phone) {
    await sendWhatsAppTemplate(
      to.phone,
      env.WHATSAPP_TEMPLATE_LEAD_ALERT,
      [GRADE_WORD[grade], name, what || '—', input.via, due ? fmtIst(due) : 'when you can', url],
      `${title}. ${input.via}.${due ? ` Call by ${fmtIst(due)}.` : ''} ${url}`,
      { tenantId: null, userId: to.id, purpose: 'LEAD_ALERT' },
    );
  }
}

/**
 * Leads nobody contacted in time, told to the super admin: one email (and
 * one WhatsApp, once approved) per tick, however many there are. Each lead
 * is reported once per arrival.
 */
export async function escalateLateLeads(now = new Date()): Promise<number> {
  const late = await prismaUnscoped.crmContact.findMany({
    where: { deletedAt: null, status: CrmContactStatus.NEW, firstTouchAt: null, escalatedAt: null, leadDueAt: { lte: now } },
    orderBy: { leadDueAt: 'asc' },
    take: 50,
    select: { id: true, firstName: true, lastName: true, companyName: true, leadGrade: true, leadDueAt: true, latestSource: true, owner: { select: { name: true } } },
  });
  if (!late.length) return 0;
  const admin = await superAdmin();
  const claimed: typeof late = [];
  for (const c of late) {
    const r = await prismaUnscoped.crmContact.updateMany({ where: { id: c.id, escalatedAt: null }, data: { escalatedAt: now } });
    if (r.count === 1) claimed.push(c);
  }
  if (!claimed.length || !admin) return claimed.length;
  const lateBy = (d: Date) => {
    const m = Math.max(1, Math.round((now.getTime() - d.getTime()) / MIN));
    return m < 60 ? `${m} min late` : `${Math.round(m / 60)} h late`;
  };
  const n = claimed.length;
  await deliver({
    key: `lead-late:${claimed.map((c) => c.id).sort().join(',').slice(0, 200)}:${now.getTime()}`,
    kind: 'LEAD_LATE',
    to: admin.email,
    userId: admin.id,
    mail: crmEmail({
      title: n === 1 ? `Not contacted in time: ${fullName(claimed[0])}` : `${n} leads not contacted in time`,
      intro: `${n === 1 ? 'This lead was' : 'These leads were'} not called or messaged within the response time.`,
      badge: 'Late lead',
      tone: 'warning',
      sections: [
        {
          heading: n === 1 ? 'Lead' : 'Leads',
          items: claimed.map((c) => ({
            text: `${fullName(c)}${c.companyName ? `, ${c.companyName}` : ''}`,
            sub: [c.leadGrade ? GRADE_WORD[c.leadGrade] : null, c.latestSource, c.owner ? `Owner: ${c.owner.name}` : 'No owner'].filter(Boolean).join(' · '),
            url: crmUrl(`contacts/${c.id}`),
            aside: lateBy(c.leadDueAt!),
            tone: 'warning' as const,
          })),
        },
      ],
      cta: { label: 'Open the CRM', url: crmUrl('contacts') },
      reason: 'You are the super admin of the HostelCare CRM.',
    }),
  });
  if (env.WHATSAPP_TEMPLATE_LEAD_OVERDUE && admin.phone) {
    const oldest = claimed[0];
    await sendWhatsAppTemplate(
      admin.phone,
      env.WHATSAPP_TEMPLATE_LEAD_OVERDUE,
      [String(n), fullName(oldest), oldest.owner?.name ?? 'nobody', crmUrl('contacts')],
      `${n} lead${n === 1 ? '' : 's'} not contacted in time. Oldest: ${fullName(oldest)}.`,
      { tenantId: null, userId: admin.id, purpose: 'LEAD_OVERDUE' },
    );
  }
  return n;
}

// ── First touch (L4) ───────────────────────────────────────────────────────

async function safely(f: () => Promise<unknown>) {
  try {
    await f();
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[crm] first message failed: ${err instanceof Error ? err.message : String(err)}`);
  }
}

export const leadLinks = (type?: CrmPropertyType | null, source = 'lead') => ({
  trialUrl: `${publicWebUrl}/start-trial?utm_source=${source}${type === CrmPropertyType.DORMITORY ? '&type=dormitory' : ''}`,
  bookUrl: `${publicSiteUrl}/book-demo/`,
});

/**
 * Message a lead by themselves: the approved WhatsApp template when they
 * agreed and we have their number, otherwise an email. Logged on the
 * timeline. Returns the channel used, or null if neither could reach them.
 */
export async function autoMessage(contactId: string, kind: 'FIRST' | 'NO_ANSWER', now = new Date()): Promise<'whatsapp' | 'email' | null> {
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id: contactId } });
  // L6: nobody who said stop hears from us again.
  if (!c || c.deletedAt || c.optedOutAt) return null;
  const first = c.firstName.trim().split(/\s+/)[0] || c.firstName;
  const links = leadLinks(c.propertyType, kind === 'FIRST' ? 'lead' : 'callback');
  const template = kind === 'FIRST' ? env.WHATSAPP_TEMPLATE_LEAD_FIRST : env.WHATSAPP_TEMPLATE_LEAD_NO_ANSWER;
  const phone = c.whatsapp || c.phone;
  let channel: 'whatsapp' | 'email' | null = null;
  if (phone && c.consentWhatsapp && template) {
    const params = kind === 'FIRST' ? [first, links.trialUrl, links.bookUrl] : [first, links.bookUrl];
    const r = await sendWhatsAppTemplate(phone, template, params, kind === 'FIRST' ? `Thanks for your interest in HostelCare. Trial: ${links.trialUrl} Demo: ${links.bookUrl}` : `We tried to call you. Book a demo: ${links.bookUrl}`, {
      tenantId: null,
      crmContactId: c.id,
      purpose: kind === 'FIRST' ? 'LEAD_FIRST' : 'LEAD_NO_ANSWER',
    });
    if (r.sent || r.mode === 'log') channel = 'whatsapp';
  }
  if (!channel && c.email) {
    const status = await deliver({ key: `touch:${c.id}:${kind}:${now.getTime()}`, kind: `LEAD_${kind}`, to: c.email, mail: leadTouchEmail(kind, { name: first, ...links, unsubscribeUrl: unsubscribeUrl(c.id) }), force: true });
    if (status !== 'FAILED' && status !== 'SKIPPED') channel = 'email';
  }
  if (channel) {
    await prismaUnscoped.crmActivity.create({
      data: { contactId: c.id, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: kind === 'FIRST' ? 'first_touch' : 'no_answer', channel } as Prisma.InputJsonValue, actorName: 'HostelCare (automatic)', createdAt: new Date(now.getTime() + 2) },
    });
  }
  return channel;
}

/** The first message to a new lead, once ever, if the super admin left it on. */
export async function sendFirstTouch(contactId: string, now = new Date()) {
  const s = await getCrmSettings();
  if (!s.autoFirstMessage) return null;
  const claimed = await prismaUnscoped.crmContact.updateMany({ where: { id: contactId, firstTouchSentAt: null }, data: { firstTouchSentAt: now } });
  if (!claimed.count) return null;
  const channel = await autoMessage(contactId, 'FIRST', now);
  // Nothing could reach them: leave it unsent, so it is not claimed falsely.
  if (!channel) await prismaUnscoped.crmContact.update({ where: { id: contactId }, data: { firstTouchSentAt: null } });
  return channel;
}

// ── Pipeline entry (L5) ────────────────────────────────────────────────────

const BED_PRICE_YEAR = 20 * 12;
const dealNumberRef = (n: number) => `DEAL-${String(n).padStart(4, '0')}`;

/** A new lead's deal at "New lead": the first call (due by the response clock) is its next step. */
async function openLeadDeal(contactId: string, ownerId: string | null, input: LeadInput, dueAt: Date | null, now: Date) {
  const c = await prismaUnscoped.crmContact.findUniqueOrThrow({ where: { id: contactId } });
  const stage = (await stageByKey(STAGE_KEYS.NEW_LEAD)) ?? (await prismaUnscoped.crmStage.findFirst({ where: { kind: 'OPEN' }, orderBy: { position: 'asc' } }));
  if (!stage) return;
  const top = await prismaUnscoped.crmDeal.aggregate({ where: { stageId: stage.id, deletedAt: null }, _max: { position: true } });
  await prismaUnscoped.$transaction(async (tx) => {
    const d = await tx.crmDeal.create({
      data: {
        title: c.companyName || fullName(c),
        stageId: stage.id,
        position: (top._max.position ?? 0) + 1,
        contactId,
        assigneeId: ownerId,
        companyName: c.companyName,
        source: input.source,
        beds: c.approxBeds,
        value: c.approxBeds ? c.approxBeds * BED_PRICE_YEAR : 0,
        nextStep: 'First call',
        nextActionAt: dueAt,
      },
    });
    await tx.crmActivity.create({ data: { dealId: d.id, contactId, type: CrmActivityType.CREATED, meta: { ref: dealNumberRef(d.number), title: d.title }, actorName: input.via, createdAt: new Date(now.getTime() + 3) } });
  });
}

/** Put a contact on a named list, making the list the first time. */
async function addToList(contactId: string, name: string, description: string, color: string, actorName: string) {
  const list = await prismaUnscoped.crmList.upsert({ where: { nameKey: name.toLowerCase() }, update: {}, create: { name, nameKey: name.toLowerCase(), description, color } });
  const added = await prismaUnscoped.crmListMember.createMany({ data: [{ listId: list.id, contactId }], skipDuplicates: true });
  if (added.count) await prismaUnscoped.crmActivity.create({ data: { contactId, type: CrmActivityType.LIST_ADDED, meta: { listId: list.id, list: list.name }, actorName } });
}
