import { CrmActivityType, CrmContactStatus, CrmLeadGrade, CrmPropertyType, CrmStageKind, Prisma, Role } from '@prisma/client';
import { env } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { crmEmail } from '../../lib/email-templates';
import { sendWhatsApp, sendWhatsAppButtons } from '../../lib/whatsapp';
import { getCrmSettings } from './crm-settings.service';
import { crmUrl, deliver, fmtIst } from './crm-mail';
import { addToNurture, fullName, getContact, markTouched, setOptOut } from './crm-contacts.service';
import { autoMessage, ingestLead, leadLinks, leadOwner, workingDue, type LeadInput } from './crm-leads.service';
import { LOST_REASONS, moveDeal, TEAM_LOST_REASONS, type LostReasonCode } from './crm-deals.service';
import type { Actor } from './crm-users.service';
import { advanceDeal } from './crm-pipeline.service';
import { STAGE_KEYS } from './crm-stages.service';

/**
 * Sprint L4: every lead hears from us, and every call ends with an outcome.
 *
 * - Call outcomes: one tap after a call. Interested, Call me later (with a
 *   time), No answer, Not interested (with a reason from a fixed list),
 *   Wrong number, Not a fit. Answered calls clear the no-answer run.
 * - No answer: the first miss sets three call-backs (3 working hours later,
 *   the next day and day 3); the second sends the "we tried to call you"
 *   message; the third moves the lead to Nurture and loses its deals.
 * - WhatsApp: a message from a number we do not know (not a CRM contact, not
 *   anyone on a hostel account) becomes a lead and gets a three-button reply:
 *   Start free trial, Book a demo, Talk to sales.
 * - Meta lead ads: the Page webhook gives a lead id; its answers are fetched
 *   with the Page token, mapped to the lead's fields, and taken in like any
 *   other enquiry (first message included).
 */

const HOUR = 3_600_000;
const DAY = 24 * HOUR;
export const RETRY_KIND = 'NO_ANSWER_RETRY';

export const CALL_OUTCOMES = ['INTERESTED', 'CALL_LATER', 'NO_ANSWER', 'NOT_INTERESTED', 'WRONG_NUMBER', 'NOT_A_FIT'] as const;
export type CallOutcome = (typeof CALL_OUTCOMES)[number];
const OUTCOME_WORD: Record<CallOutcome, string> = {
  INTERESTED: 'Interested',
  CALL_LATER: 'Call me later',
  NO_ANSWER: 'No answer',
  NOT_INTERESTED: 'Not interested',
  WRONG_NUMBER: 'Wrong number',
  NOT_A_FIT: 'Not a fit',
};

// ── Call outcomes ──────────────────────────────────────────────────────────

/** Lose every open deal of a contact with one reason. */
async function loseOpenDeals(contactId: string, code: LostReasonCode, actor: Actor, detail?: string | null) {
  const lost = await prismaUnscoped.crmStage.findFirst({ where: { kind: CrmStageKind.LOST } });
  if (!lost) return 0;
  const open = await prismaUnscoped.crmDeal.findMany({ where: { contactId, deletedAt: null, stage: { kind: CrmStageKind.OPEN } }, select: { id: true } });
  for (const d of open) {
    await moveDeal(d.id, { stageId: lost.id, lostReasonCode: code, lostReason: detail?.trim() ? `${LOST_REASONS[code]}: ${detail.trim()}` : LOST_REASONS[code] }, actor);
  }
  return open.length;
}

async function closeRetries(contactId: string, now: Date) {
  return (await prismaUnscoped.crmTask.updateMany({ where: { contactId, kind: RETRY_KIND, done: false }, data: { done: true, doneAt: now } })).count;
}

/** 3 working hours later, the next working day, and day 3 — always in that order. */
export function retryTimes(now: Date, s: Parameters<typeof workingDue>[1]) {
  const at = (from: Date, minutes = 0) => workingDue(from, { ...s, responseMinutes: minutes });
  const first = at(now, 180);
  const second = at(new Date(Math.max(now.getTime() + DAY, first.getTime() + 3 * HOUR)));
  const third = at(new Date(Math.max(now.getTime() + 3 * DAY, second.getTime() + DAY)));
  return [first, second, third];
}

export interface OutcomeInput {
  outcome: CallOutcome;
  note?: string | null;
  followUpAt?: Date | null;
  reason?: (typeof TEAM_LOST_REASONS)[number] | null;
}

export async function logCallOutcome(contactId: string, input: OutcomeInput, actor: Actor, now = new Date()) {
  const c = await prismaUnscoped.crmContact.findFirst({ where: { id: contactId, deletedAt: null } });
  if (!c) throw new NotFoundError('Contact not found');
  if (input.outcome === 'CALL_LATER' && !input.followUpAt) throw new BadRequestError('Say when to call back.', 'FOLLOW_UP_REQUIRED');
  if (input.outcome === 'NOT_INTERESTED' && !input.reason) throw new BadRequestError('Pick why they are not interested.', 'REASON_REQUIRED');
  if (input.followUpAt && input.followUpAt.getTime() < now.getTime() - 60_000) throw new BadRequestError('The call-back time has passed.', 'FOLLOW_UP_PAST');

  const answered = input.outcome !== 'NO_ANSWER';
  const misses = answered ? 0 : c.noAnswerCount + 1;
  const result = { outcome: input.outcome, misses, retriesCreated: 0, messaged: null as 'whatsapp' | 'email' | null, nurtured: false, dealsLost: 0 };

  const data: Prisma.CrmContactUncheckedUpdateInput = { lastOutcome: input.outcome, lastOutcomeAt: now, noAnswerCount: misses, updatedById: actor.id };
  if (answered) data.lastContactedAt = now;
  if (input.outcome === 'INTERESTED') {
    if (c.status === CrmContactStatus.NEW || c.status === CrmContactStatus.CONTACTED || c.status === CrmContactStatus.LOST) data.status = CrmContactStatus.QUALIFIED;
    if (input.followUpAt) data.nextFollowUpAt = input.followUpAt;
  } else if (input.outcome === 'CALL_LATER') {
    if (c.status === CrmContactStatus.NEW) data.status = CrmContactStatus.CONTACTED;
    data.nextFollowUpAt = input.followUpAt!;
  } else if (input.outcome === 'NOT_INTERESTED' || input.outcome === 'WRONG_NUMBER' || input.outcome === 'NOT_A_FIT') {
    if (c.status !== CrmContactStatus.CUSTOMER) data.status = CrmContactStatus.LOST;
    data.nextFollowUpAt = null;
    if (input.outcome === 'NOT_A_FIT') data.leadGrade = CrmLeadGrade.NOT_A_FIT;
  }

  const reasonLabel = input.reason ? LOST_REASONS[input.reason] : null;
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmContact.update({ where: { id: c.id }, data }),
    prismaUnscoped.crmActivity.create({
      data: {
        contactId: c.id,
        type: CrmActivityType.CALL,
        body: input.note?.trim().slice(0, 2000) || null,
        meta: {
          outcome: input.outcome,
          label: OUTCOME_WORD[input.outcome],
          ...(reasonLabel ? { reason: reasonLabel } : {}),
          ...(input.followUpAt ? { followUpAt: input.followUpAt.toISOString() } : {}),
          ...(!answered ? { misses } : {}),
        } as Prisma.InputJsonValue,
        actorId: actor.id,
        actorName: actor.name,
        createdAt: now,
      },
    }),
  ]);
  // Any call, answered or not, is the first contact for the response clock.
  await markTouched(c.id, now);

  if (answered) await closeRetries(c.id, now);
  // L5: a first real conversation moves a 'New lead' deal on to 'Contacted', with its next step dated.
  if (input.outcome === 'INTERESTED' || input.outcome === 'CALL_LATER') {
    const s = await getCrmSettings();
    const nextAt = input.followUpAt ?? workingDue(new Date(now.getTime() + DAY), { ...s, responseMinutes: 60 });
    const open = await prismaUnscoped.crmDeal.findMany({ where: { contactId: c.id, deletedAt: null, stage: { key: STAGE_KEYS.NEW_LEAD } }, select: { id: true } });
    for (const d of open) await advanceDeal(d.id, STAGE_KEYS.CONTACTED, actor, { nextStep: input.outcome === 'CALL_LATER' ? 'Call back' : 'Follow up: book the demo or start the trial', nextActionAt: nextAt });
  }

  if (input.outcome === 'NOT_INTERESTED') {
    result.dealsLost = await loseOpenDeals(c.id, input.reason!, actor, input.reason === 'OTHER' ? input.note : null);
    // Not now is not never (L6): they join Nurture even with no deal to lose.
    await addToNurture(c.id, actor);
  }
  if (input.outcome === 'WRONG_NUMBER') result.dealsLost = await loseOpenDeals(c.id, 'WRONG_NUMBER', actor);
  if (input.outcome === 'NOT_A_FIT') result.dealsLost = await loseOpenDeals(c.id, 'NOT_A_FIT', actor);

  if (!answered) {
    // This call was one of the planned call-backs: tick it off.
    if (misses > 1) {
      const due = await prismaUnscoped.crmTask.findFirst({ where: { contactId: c.id, kind: RETRY_KIND, done: false }, orderBy: { dueAt: 'asc' } });
      if (due) await prismaUnscoped.crmTask.update({ where: { id: due.id }, data: { done: true, doneAt: now } });
    }
    if (misses === 1) result.retriesCreated = await planRetries(c, actor, now);
    if (misses === 2) result.messaged = await autoMessage(c.id, 'NO_ANSWER', now);
    if (misses >= 3) {
      await addToNurture(c.id, actor);
      await closeRetries(c.id, now);
      await prismaUnscoped.crmContact.update({ where: { id: c.id }, data: { status: c.status === CrmContactStatus.CUSTOMER ? c.status : CrmContactStatus.LOST } });
      result.dealsLost = await loseOpenDeals(c.id, 'NO_ANSWER', actor);
      result.nurtured = true;
    }
  }
  return { contact: await getContact(c.id), result };
}

async function planRetries(c: { id: string; firstName: string; lastName: string | null; ownerId: string | null }, actor: Actor, now: Date) {
  const s = await getCrmSettings();
  const assigneeId = c.ownerId ?? actor.id;
  const deal = await prismaUnscoped.crmDeal.findFirst({ where: { contactId: c.id, deletedAt: null, stage: { kind: CrmStageKind.OPEN } }, orderBy: { updatedAt: 'desc' }, select: { id: true } });
  const name = fullName(c);
  const times = retryTimes(now, s);
  const titles = [`Call ${name} again (no answer)`, `Call ${name} again (2nd try)`, `Call ${name} again (last try)`];
  await prismaUnscoped.crmTask.createMany({
    data: times.map((dueAt, i) => ({ title: titles[i], dueAt, assigneeId, contactId: c.id, dealId: deal?.id ?? null, kind: RETRY_KIND, createdById: actor.id })),
  });
  return times.length;
}

/** Open tasks about a contact (the call-backs), for its page. */
export async function contactTasks(contactId: string) {
  const rows = await prismaUnscoped.crmTask.findMany({
    where: { contactId, done: false },
    orderBy: { dueAt: 'asc' },
    take: 20,
    include: { assignee: { select: { id: true, name: true } } },
  });
  return rows.map((t) => ({ id: t.id, title: t.title, dueAt: t.dueAt, kind: t.kind, assignee: t.assignee }));
}

// ── STOP and START (L6) ────────────────────────────────────────────────────

export const isStopWord = (body: string) => /^(stop|stop all|stop promotions?|unsubscribe|opt out|optout|cancel|end|quit|बंद)$/i.test(body.trim().replace(/[.!]+$/, ''));
export const isStartWord = (body: string) => /^(start|unstop|subscribe|resume)$/i.test(body.trim().replace(/[.!]+$/, ''));

/**
 * A CRM contact replying STOP stops every automatic message (and says so
 * once); START brings them back. Returns whether the message was one of these.
 */
export async function onWhatsAppKeyword(contactId: string, body: string, profileName: string | null, now = new Date()) {
  const stop = isStopWord(body);
  if (!stop && !isStartWord(body)) return false;
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id: contactId }, select: { id: true, phone: true, whatsapp: true, firstName: true } });
  if (!c) return false;
  const changed = await setOptOut(c.id, stop, 'whatsapp', { id: null, name: profileName || 'Their WhatsApp reply' }, now);
  const phone = (c.whatsapp || c.phone || '').replace(/\D/g, '');
  if (changed && phone) {
    await sendWhatsApp(phone, stop ? "You're unsubscribed: HostelCare won't message you again. Reply START if you change your mind." : "You're subscribed again to HostelCare messages. Reply STOP any time to stop them.", { tenantId: null, crmContactId: c.id, purpose: 'LEAD_REPLY' });
  }
  return true;
}

// ── WhatsApp from a number we do not know ──────────────────────────────────

export const WA_BUTTONS = [
  { id: 'HC_TRIAL', title: 'Start free trial' },
  { id: 'HC_DEMO', title: 'Book a demo' },
  { id: 'HC_SALES', title: 'Talk to sales' },
] as const;

/** Anyone on a hostel account (owner, staff, student, guardian) with this number. */
async function onAHostelAccount(phoneKey: string) {
  const rows = await prismaUnscoped.$queryRaw<{ id: string }[]>`
    SELECT "id" FROM "User"
    WHERE "tenantId" IS NOT NULL AND "phone" IS NOT NULL
      AND right(regexp_replace("phone", '[^0-9]', '', 'g'), 10) = ${phoneKey}
    LIMIT 1`;
  return rows.length > 0;
}

/**
 * A message nobody can place becomes a lead (source "WhatsApp"), with the
 * three-button reply. Returns the new contact's id, or null when the number
 * belongs to a hostel account (a student's question is not a sales lead).
 */
export async function leadFromWhatsApp(p: { phone: string; profileName: string | null; body: string; waMessageId: string }, now = new Date()): Promise<string | null> {
  const digits = p.phone.replace(/\D/g, '');
  const key = digits.slice(-10);
  if (key.length < 10 || (await onAHostelAccount(key))) return null;
  // A first message that only says STOP is not a lead (L6).
  if (isStopWord(p.body)) return null;
  const name = p.profileName && /\p{L}/u.test(p.profileName) && p.profileName.trim().length >= 2 ? p.profileName.trim() : `WhatsApp +${digits}`;
  const input: LeadInput = {
    name,
    phone: `+${digits}`,
    source: 'WhatsApp',
    via: 'WhatsApp message',
    message: p.body.slice(0, 1000) || null,
    // They wrote to us there: replying on WhatsApp is what they asked for.
    consent: true,
    // The button reply below is their first message.
    firstTouch: false,
  };
  const r = await ingestLead(input, now);
  await prismaUnscoped.whatsAppMessage.updateMany({ where: { waMessageId: p.waMessageId }, data: { crmContactId: r.contactId } });
  const s = await getCrmSettings();
  if (s.waAutoReply && r.created) {
    const first = name.startsWith('WhatsApp +') ? '' : ` ${name.split(/\s+/)[0]}`;
    const sent = await sendWhatsAppButtons(digits, `Hi${first}, thanks for messaging HostelCare — software for hostels and dormitories. How can we help?`, [...WA_BUTTONS], { tenantId: null, crmContactId: r.contactId, purpose: 'LEAD_REPLY' });
    if (sent.sent || sent.mode === 'log') {
      await prismaUnscoped.crmContact.update({ where: { id: r.contactId }, data: { firstTouchSentAt: now } });
      await prismaUnscoped.crmActivity.create({ data: { contactId: r.contactId, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: 'wa_buttons', channel: 'whatsapp' }, actorName: 'HostelCare (automatic)', createdAt: new Date(now.getTime() + 2) } });
    }
  }
  return r.contactId;
}

/** A tap on one of the three buttons, from a CRM contact. */
export async function onWhatsAppButton(contactId: string, buttonId: string, now = new Date()) {
  const c = await prismaUnscoped.crmContact.findUnique({ where: { id: contactId } });
  if (!c || c.deletedAt) return;
  const phone = (c.whatsapp || c.phone || '').replace(/\D/g, '');
  if (!phone) return;
  const links = leadLinks(c.propertyType, 'whatsapp');
  const ctx = { tenantId: null, crmContactId: c.id, purpose: 'LEAD_REPLY' as const };
  let reply: string | null = null;
  if (buttonId === 'HC_TRIAL') reply = `Start your free 7-day trial here — set up your rooms in two minutes, no card needed:\n${links.trialUrl}`;
  if (buttonId === 'HC_DEMO') reply = `Pick a time for a free 15-minute demo on Google Meet (Hindi or English):\n${links.bookUrl}`;
  if (buttonId === 'HC_SALES') {
    reply = 'Thank you! Someone from our team will call you within working hours (Monday to Saturday, 10 am – 7 pm).';
    await askedForSales(c, now);
  }
  if (!reply) return;
  await sendWhatsApp(phone, reply, ctx);
  await prismaUnscoped.crmActivity.create({ data: { contactId: c.id, type: CrmActivityType.AUTO_MESSAGE, meta: { purpose: `wa_${buttonId.slice(3).toLowerCase()}`, channel: 'whatsapp' }, actorName: 'HostelCare (automatic)', createdAt: new Date(now.getTime() + 2) } });
}

/** "Talk to sales": a call-back task due now and an email to the owner straight away. */
async function askedForSales(c: Prisma.CrmContactGetPayload<object>, now: Date) {
  const s = await getCrmSettings();
  const owner =
    (c.ownerId ? await prismaUnscoped.user.findFirst({ where: { id: c.ownerId, deactivatedAt: null, role: { in: [Role.CRM_USER, Role.SUPER_ADMIN] } }, select: { id: true, name: true, email: true } }) : null) ??
    (await leadOwner(s));
  const name = fullName(c);
  const due = workingDue(now, { ...s, responseMinutes: Math.min(s.responseMinutes, 60) });
  await prismaUnscoped.crmTask.create({ data: { title: `Call ${name} — asked to talk to sales on WhatsApp`, dueAt: due, assigneeId: owner?.id ?? null, contactId: c.id, kind: 'WA_SALES' } });
  if (!owner) return;
  const url = crmUrl(`contacts/${c.id}`);
  await deliver({
    key: `wa-sales:${c.id}:${now.getTime()}`,
    kind: 'LEAD',
    to: owner.email,
    userId: owner.id,
    mail: crmEmail({
      title: `Call ${name}: asked for sales on WhatsApp`,
      intro: `${name} tapped "Talk to sales" on WhatsApp. Call by ${fmtIst(due)}.`,
      badge: 'Call back',
      tone: 'warning',
      sections: [{ heading: 'Lead', items: [{ text: name, sub: c.companyName ?? undefined, url }, ...(c.phone ? [{ text: c.phone, sub: 'Phone (WhatsApp)' }] : [])] }],
      cta: { label: 'Open the lead', url },
      reason: 'You own this lead in the HostelCare CRM.',
    }),
  });
}

// ── Meta lead ads ──────────────────────────────────────────────────────────

export interface MetaLeadEvent {
  leadgen_id?: string;
  page_id?: string;
  form_id?: string;
  ad_id?: string;
}

/** Keep each lead id once (Meta resends), then work them. */
export async function recordMetaLeads(events: MetaLeadEvent[]) {
  const rows = events.filter((e) => e.leadgen_id).map((e) => ({ leadgenId: String(e.leadgen_id), pageId: e.page_id ? String(e.page_id) : null, formId: e.form_id ? String(e.form_id) : null, adId: e.ad_id ? String(e.ad_id) : null }));
  if (!rows.length) return [];
  await prismaUnscoped.metaLead.createMany({ data: rows, skipDuplicates: true });
  return rows.map((r) => r.leadgenId);
}

interface FieldDatum {
  name?: string;
  values?: string[];
}

const truthy = (v: string) => /^(yes|y|true|1|ok|okay|agree|i agree|haan|ha|sure)\b/i.test(v.trim());

/**
 * Meta lead form answers → lead fields. Standard questions have fixed keys
 * (full_name, phone_number, email, city); custom ones are keyed by their
 * question, so they are matched by the words in them.
 */
export function mapLeadFields(fields: FieldDatum[]) {
  const out: { name?: string; first?: string; last?: string; phone?: string; email?: string; city?: string; state?: string; hostelName?: string; beds?: number; type?: CrmPropertyType; notFit?: boolean; consent?: boolean; answers: string[] } = { answers: [] };
  for (const f of fields) {
    const key = (f.name ?? '').toLowerCase();
    const value = (f.values?.[0] ?? '').trim();
    if (!key || !value) continue;
    out.answers.push(`${key.replace(/_/g, ' ').replace(/\?$/, '')}: ${value}`);
    if (key === 'full_name' || key === 'name') out.name = value;
    else if (key === 'first_name') out.first = value;
    else if (key === 'last_name') out.last = value;
    else if (key === 'email' || key.includes('email')) out.email = value;
    else if (key.includes('phone') || key.includes('mobile') || (key.includes('whatsapp') && /\d{7,}/.test(value.replace(/\D/g, '')))) out.phone = value;
    else if (key === 'city' || key.includes('city')) out.city = value;
    else if (key === 'state' || key === 'province') out.state = value;
    else if (key.includes('bed')) {
      const n = Number((value.match(/\d+/) ?? [''])[0]);
      if (Number.isFinite(n) && n > 0) out.beds = Math.min(n, 100_000);
    } else if (key.includes('company') || key.includes('hostel_name') || key.includes('property_name') || key.includes('business_name') || (key.includes('name') && (key.includes('hostel') || key.includes('dorm')))) out.hostelName = value;
    else if (key.includes('whatsapp') || key.includes('consent') || key.includes('contact_you')) out.consent = truthy(value);
    else if (key.includes('type') || key.includes('hostel') || key.includes('dorm') || key.includes('property') || key.includes('run')) {
      const v = value.toLowerCase();
      if (v.includes('dorm')) out.type = CrmPropertyType.DORMITORY;
      else if (/\bpg\b|paying guest/.test(v)) out.type = CrmPropertyType.PG;
      else if (v.includes('hostel')) out.type = CrmPropertyType.HOSTEL;
      else if (v.includes('student') || v.includes('looking')) out.notFit = true;
      else out.type = CrmPropertyType.OTHER;
    }
  }
  if (!out.name && (out.first || out.last)) out.name = [out.first, out.last].filter(Boolean).join(' ');
  return out;
}

interface GraphLead {
  id?: string;
  created_time?: string;
  field_data?: FieldDatum[];
  ad_id?: string;
  ad_name?: string;
  adset_name?: string;
  campaign_name?: string;
  form_id?: string;
  platform?: string;
  is_organic?: boolean;
  error?: { message?: string; code?: number };
}

/** Fetch one lead's answers and take it into the CRM. Safe to call twice. */
export async function processMetaLead(leadgenId: string, now = new Date()) {
  const claim = await prismaUnscoped.metaLead.updateMany({
    where: { leadgenId, OR: [{ status: 'PENDING' }, { status: 'FAILED', attempts: { lt: 5 } }, { status: 'WORKING', createdAt: { lt: new Date(now.getTime() - 10 * 60_000) } }] },
    data: { status: 'WORKING', attempts: { increment: 1 } },
  });
  if (!claim.count) return null;
  const fail = (error: string) => prismaUnscoped.metaLead.update({ where: { leadgenId }, data: { status: 'FAILED', error: error.slice(0, 300) } });
  if (!env.META_PAGE_ACCESS_TOKEN) {
    await fail('META_PAGE_ACCESS_TOKEN is not set on the server');
    return null;
  }
  let lead: GraphLead;
  try {
    const fields = 'field_data,created_time,ad_id,ad_name,adset_name,campaign_name,form_id,platform,is_organic';
    const res = await fetch(`${env.WHATSAPP_API_BASE}/${encodeURIComponent(leadgenId)}?fields=${fields}&access_token=${encodeURIComponent(env.META_PAGE_ACCESS_TOKEN)}`);
    lead = (await res.json().catch(() => ({}))) as GraphLead;
    if (!res.ok || lead.error) {
      await fail(lead.error?.message ? `${lead.error.code ?? res.status}: ${lead.error.message}` : `HTTP ${res.status}`);
      return null;
    }
  } catch (err) {
    await fail(err instanceof Error ? err.message : String(err));
    return null;
  }
  const f = mapLeadFields(lead.field_data ?? []);
  if (!f.phone && !f.email) {
    await fail('The lead has no phone number or email');
    return null;
  }
  const platform = lead.platform === 'ig' ? 'Instagram' : lead.platform === 'fb' ? 'Facebook' : null;
  const meta: Record<string, string> = {};
  if (lead.campaign_name) meta.utmCampaign = lead.campaign_name;
  if (lead.ad_name) meta.adName = lead.ad_name;
  if (lead.adset_name) meta.adSet = lead.adset_name;
  if (lead.form_id) meta.formId = lead.form_id;
  if (platform) meta.platform = platform;
  meta.metaLeadId = leadgenId;
  const r = await ingestLead(
    {
      name: f.name && f.name.length >= 2 ? f.name : f.phone ?? f.email ?? 'Meta lead',
      phone: f.phone ?? null,
      email: f.email ?? null,
      hostelName: f.hostelName ?? null,
      type: f.type ?? null,
      beds: f.beds ?? null,
      city: f.city ?? null,
      state: f.state ?? null,
      notFit: f.notFit,
      consent: f.consent ?? false,
      message: f.answers.join('\n').slice(0, 1000) || null,
      source: 'Meta ads',
      via: platform ? `Meta lead form (${platform})` : 'Meta lead form',
      meta,
    },
    now,
  );
  await prismaUnscoped.metaLead.update({ where: { leadgenId }, data: { status: 'DONE', error: null, contactId: r.contactId, processedAt: now, raw: lead as unknown as Prisma.InputJsonValue } });
  return r.contactId;
}

/** The CRM clock: work leads that are waiting or failed (a token fixed later, Meta briefly down). */
export async function retryMetaLeads(now = new Date()) {
  const due = await prismaUnscoped.metaLead.findMany({
    where: {
      OR: [
        { status: 'PENDING', createdAt: { lt: new Date(now.getTime() - 60_000) } },
        { status: 'FAILED', attempts: { lt: 5 } },
        { status: 'WORKING', createdAt: { lt: new Date(now.getTime() - 10 * 60_000) } },
      ],
    },
    take: 50,
    select: { leadgenId: true },
  });
  let done = 0;
  for (const d of due) if (await processMetaLead(d.leadgenId, now)) done++;
  return done;
}

/** For the super admin: the latest Meta leads and how they went. */
export async function metaLeadLog(limit = 50) {
  return prismaUnscoped.metaLead.findMany({ orderBy: { createdAt: 'desc' }, take: Math.min(limit, 200), select: { leadgenId: true, status: true, attempts: true, error: true, contactId: true, formId: true, adId: true, createdAt: true, processedAt: true } });
}
