import { CrmContactStatus, CrmDemoStatus, CrmStageKind, Prisma } from '@prisma/client';
import { env, publicSiteUrl } from '../../config/env';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { nurtureEmail } from '../../lib/email-templates';
import { sendWhatsAppTemplate } from '../../lib/whatsapp';
import { getCrmSettings } from './crm-settings.service';
import { deliver } from './crm-mail';
import { fullName, unsubscribeUrl } from './crm-contacts.service';
import { leadOwner } from './crm-leads.service';
import { LOST_REASONS } from './crm-deals.service';
import { STAGE_KEYS } from './crm-stages.service';
import type { Actor } from './crm-users.service';

/**
 * Nurture and reporting (Sprint L6).
 *
 * - Nurture: leads who are not ready (the "Nurture" list — lost leads except
 *   wrong numbers and non-fits, three unanswered calls, two missed demos,
 *   unused trials — and the "PG – later" list) get one message a month: an
 *   email with the month's best blog or tip, and at most one WhatsApp
 *   template to those who agreed. Nobody who opted out. Sent in batches by
 *   the CRM clock, so the email provider's limits are never hit.
 * - Admission season: each April, a call task for every nurture lead,
 *   spread over the working days of April and May.
 * - The funnel: leads → contacted → demos → trials → active → paid, by
 *   source and campaign, with the 1-hour habit, demo show-up, lost reasons
 *   and cost per lead / per paying hostel from the spend entered monthly.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;
const NURTURE_LISTS = ['nurture', 'pg – later'];
const BATCH = 40;
const istDate = (d: Date) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 10);
const monthOf = (d: Date) => istDate(d).slice(0, 7);

// ── Audience ───────────────────────────────────────────────────────────────

async function nurtureContacts(includeOptedOut = false) {
  return prismaUnscoped.crmContact.findMany({
    where: { deletedAt: null, ...(includeOptedOut ? {} : { optedOutAt: null }), lists: { some: { list: { nameKey: { in: NURTURE_LISTS } } } } },
    select: { id: true, firstName: true, lastName: true, email: true, phone: true, whatsapp: true, consentWhatsapp: true, optedOutAt: true, ownerId: true },
    take: 20_000,
  });
}

export async function audience() {
  const all = await nurtureContacts(true);
  const live = all.filter((c) => !c.optedOutAt);
  return {
    total: all.length,
    optedOut: all.length - live.length,
    email: live.filter((c) => !!c.email).length,
    whatsapp: live.filter((c) => (c.whatsapp || c.phone) && c.consentWhatsapp).length,
    whatsappTemplate: !!env.WHATSAPP_TEMPLATE_NURTURE,
  };
}

// ── Campaigns ──────────────────────────────────────────────────────────────

export interface CampaignInput {
  month: string;
  subject: string;
  body: string;
  linkUrl?: string | null;
  linkLabel?: string | null;
  whatsapp?: boolean;
}

export async function listCampaigns() {
  return prismaUnscoped.crmNurtureCampaign.findMany({ orderBy: { month: 'desc' }, take: 24 });
}

export async function saveCampaign(id: string | null, input: CampaignInput, actor: Actor) {
  const data = { month: input.month, subject: input.subject.trim(), body: input.body.trim(), linkUrl: input.linkUrl?.trim() || null, linkLabel: input.linkLabel?.trim() || null, whatsapp: !!input.whatsapp };
  if (id) {
    const c = await prismaUnscoped.crmNurtureCampaign.findUnique({ where: { id } });
    if (!c) throw new NotFoundError('Campaign not found');
    if (c.status !== 'DRAFT') throw new ConflictError('This month’s message has already gone out.', 'CAMPAIGN_SENT');
    return prismaUnscoped.crmNurtureCampaign.update({ where: { id }, data });
  }
  try {
    return await prismaUnscoped.crmNurtureCampaign.create({ data: { ...data, createdById: actor.id } });
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') throw new ConflictError(`There is already a nurture message for ${input.month}. Edit that one.`, 'CAMPAIGN_EXISTS');
    throw e;
  }
}

export async function deleteCampaign(id: string) {
  const c = await prismaUnscoped.crmNurtureCampaign.findUnique({ where: { id } });
  if (!c) throw new NotFoundError('Campaign not found');
  if (c.status !== 'DRAFT') throw new ConflictError('A message that has gone out stays on record.', 'CAMPAIGN_SENT');
  await prismaUnscoped.crmNurtureCampaign.delete({ where: { id } });
}

/** Freeze the audience and start sending; the CRM clock does the rest in batches. */
export async function startCampaign(id: string, now = new Date()) {
  const c = await prismaUnscoped.crmNurtureCampaign.findUnique({ where: { id } });
  if (!c) throw new NotFoundError('Campaign not found');
  if (c.status !== 'DRAFT') throw new ConflictError('This message is already going out.', 'CAMPAIGN_SENT');
  const people = await nurtureContacts();
  if (!people.length) throw new BadRequestError('Nobody is on the nurture lists yet.', 'NO_AUDIENCE');
  await prismaUnscoped.$transaction([
    prismaUnscoped.crmNurtureSend.createMany({ data: people.map((p) => ({ campaignId: id, contactId: p.id })), skipDuplicates: true }),
    prismaUnscoped.crmNurtureCampaign.update({ where: { id }, data: { status: 'SENDING', startedAt: now, total: people.length } }),
  ]);
  return prismaUnscoped.crmNurtureCampaign.findUniqueOrThrow({ where: { id } });
}

/** One batch per campaign per tick. */
export async function nurtureTick(now = new Date()) {
  let sent = 0;
  for (const c of await prismaUnscoped.crmNurtureCampaign.findMany({ where: { status: 'SENDING' } })) {
    const batch = await prismaUnscoped.crmNurtureSend.findMany({ where: { campaignId: c.id, emailAt: null, whatsappAt: null, skipped: null }, include: { contact: true }, take: BATCH });
    for (const s of batch) {
      const p = s.contact;
      // Checked again at send time: someone may have said stop since it started.
      if (p.deletedAt || p.optedOutAt) {
        await prismaUnscoped.crmNurtureSend.update({ where: { campaignId_contactId: { campaignId: c.id, contactId: p.id } }, data: { skipped: p.optedOutAt ? 'opted out' : 'deleted' } });
        continue;
      }
      const first = p.firstName.trim().split(/\s+/)[0] || p.firstName;
      let emailAt: Date | null = null;
      let whatsappAt: Date | null = null;
      if (p.email) {
        const status = await deliver({ key: `nurture:${c.id}:${p.id}`, kind: 'NURTURE', to: p.email, mail: nurtureEmail({ name: first, subject: c.subject, body: c.body, linkUrl: c.linkUrl, linkLabel: c.linkLabel, unsubscribeUrl: unsubscribeUrl(p.id) }), force: true });
        if (status !== 'FAILED' && status !== 'SKIPPED') emailAt = now;
      }
      const phone = p.whatsapp || p.phone;
      if (c.whatsapp && env.WHATSAPP_TEMPLATE_NURTURE && phone && p.consentWhatsapp) {
        const r = await sendWhatsAppTemplate(phone, env.WHATSAPP_TEMPLATE_NURTURE, [first, c.linkUrl || publicSiteUrl], c.subject, { tenantId: null, crmContactId: p.id, purpose: 'LEAD_FIRST' });
        if (r.sent || r.mode === 'log') whatsappAt = now;
      }
      await prismaUnscoped.crmNurtureSend.update({
        where: { campaignId_contactId: { campaignId: c.id, contactId: p.id } },
        data: { emailAt, whatsappAt, skipped: emailAt || whatsappAt ? null : 'no email or WhatsApp' },
      });
      if (emailAt || whatsappAt) sent++;
    }
    const [emailed, whatsapped, left] = await Promise.all([
      prismaUnscoped.crmNurtureSend.count({ where: { campaignId: c.id, emailAt: { not: null } } }),
      prismaUnscoped.crmNurtureSend.count({ where: { campaignId: c.id, whatsappAt: { not: null } } }),
      prismaUnscoped.crmNurtureSend.count({ where: { campaignId: c.id, emailAt: null, whatsappAt: null, skipped: null } }),
    ]);
    await prismaUnscoped.crmNurtureCampaign.update({ where: { id: c.id }, data: { emailed, whatsapped, ...(left === 0 ? { status: 'SENT', sentAt: now } : {}) } });
  }
  return sent;
}

// ── Admission season ───────────────────────────────────────────────────────

/** Each April (or on demand): a call task for every nurture lead, over April and May's working days. */
export async function seasonCalls(now = new Date(), force = false) {
  const s = await getCrmSettings();
  const today = istDate(now);
  const year = Number(today.slice(0, 4));
  const month = Number(today.slice(5, 7));
  if (!force && (month !== 4 || s.seasonCallsYear === year)) return 0;
  if (force && s.seasonCallsYear === year) throw new ConflictError(`The admission-season calls for ${year} are already made.`, 'SEASON_DONE');
  const claim = await prismaUnscoped.crmSettings.updateMany({ where: { id: 'singleton', OR: [{ seasonCallsYear: null }, { seasonCallsYear: { not: year } }] }, data: { seasonCallsYear: year } });
  if (!claim.count) return 0;
  const people = (await nurtureContacts()).filter((p) => p.phone || p.whatsapp);
  if (!people.length) return 0;
  // Working days from today (or 1 April) to 31 May, at 11 am.
  const days: string[] = [];
  const workDays = new Set(s.workDays);
  for (let t = Date.parse(`${today < `${year}-04-01` ? `${year}-04-01` : today}T12:00:00Z`); istDate(new Date(t)) <= `${year}-05-31`; t += DAY) {
    const d = new Date(t);
    if (workDays.has(d.getUTCDay())) days.push(d.toISOString().slice(0, 10));
  }
  if (!days.length) days.push(today);
  const owner = await leadOwner(s);
  const busy = new Set((await prismaUnscoped.crmTask.findMany({ where: { kind: 'SEASON_CALL', done: false, contactId: { in: people.map((p) => p.id) } }, select: { contactId: true } })).map((t) => t.contactId));
  const todo = people.filter((p) => !busy.has(p.id));
  await prismaUnscoped.crmTask.createMany({
    data: todo.map((p, i) => ({
      title: `Admission season: call ${fullName(p)}`,
      dueAt: new Date(`${days[Math.floor((i * days.length) / todo.length)]}T11:00:00+05:30`),
      assigneeId: p.ownerId ?? owner?.id ?? null,
      contactId: p.id,
      kind: 'SEASON_CALL',
    })),
  });
  return todo.length;
}

// ── Spend ──────────────────────────────────────────────────────────────────

export async function listSpend(months = 12, now = new Date()) {
  const from = monthOf(new Date(now.getTime() - (months - 1) * 31 * DAY));
  return prismaUnscoped.crmMarketingSpend.findMany({ where: { month: { gte: from } }, orderBy: [{ month: 'desc' }, { source: 'asc' }, { campaign: 'asc' }] });
}

export async function setSpend(input: { month: string; source: string; campaign?: string | null; amount: number }, actor: Actor) {
  const key = { month: input.month, source: input.source.trim(), campaign: input.campaign?.trim() ?? '' };
  return prismaUnscoped.crmMarketingSpend.upsert({
    where: { month_source_campaign: key },
    update: { amount: input.amount },
    create: { ...key, amount: input.amount, createdById: actor.id },
  });
}

export async function deleteSpend(id: string) {
  const r = await prismaUnscoped.crmMarketingSpend.deleteMany({ where: { id } });
  if (!r.count) throw new NotFoundError('Spend entry not found');
}

// ── The funnel ─────────────────────────────────────────────────────────────

export interface FunnelRow {
  label: string;
  leads: number;
  contacted: number;
  onTime: number;
  onClock: number;
  demos: number;
  trials: number;
  active: number;
  paid: number;
  spend: number | null;
  costPerLead: number | null;
  costPerPaid: number | null;
}

/** Leads that arrived in [from, to), and how far each has got by now. */
export async function funnel(from: Date, to: Date) {
  const contacts = await prismaUnscoped.crmContact.findMany({
    where: { deletedAt: null, createdAt: { gte: from, lt: to } },
    select: { id: true, source: true, leadGrade: true, firstTouchAt: true, lastContactedAt: true, leadDueAt: true, tenantId: true, status: true, firstCampaign: true },
    take: 20_000,
  });
  const ids = contacts.map((c) => c.id);
  const [demoRows, dealRows, shows, lostRows, spendRows] = await Promise.all([
    prismaUnscoped.crmDemo.findMany({ where: { contactId: { in: ids }, status: { not: CrmDemoStatus.CANCELLED } }, select: { contactId: true }, distinct: ['contactId'] }),
    prismaUnscoped.crmDeal.findMany({ where: { contactId: { in: ids }, deletedAt: null, OR: [{ stage: { key: STAGE_KEYS.TRIAL_ACTIVE } }, { stage: { kind: CrmStageKind.WON } }] }, select: { contactId: true, stage: { select: { kind: true } } } }),
    prismaUnscoped.crmDemo.groupBy({ by: ['status'], where: { startsAt: { gte: from, lt: to }, status: { in: [CrmDemoStatus.DONE, CrmDemoStatus.NO_SHOW] } }, _count: { _all: true } }),
    prismaUnscoped.crmDeal.groupBy({ by: ['lostReasonCode'], where: { deletedAt: null, lostAt: { gte: from, lt: to } }, _count: { _all: true } }),
    prismaUnscoped.crmMarketingSpend.findMany({ where: { month: { gte: monthOf(from), lte: monthOf(new Date(to.getTime() - 1)) } } }),
  ]);
  const demoed = new Set(demoRows.map((d) => d.contactId));
  const won = new Set(dealRows.filter((d) => d.stage.kind === CrmStageKind.WON).map((d) => d.contactId));
  const active = new Set(dealRows.map((d) => d.contactId));
  const paidOf = (c: (typeof contacts)[number]) => won.has(c.id) || c.status === CrmContactStatus.CUSTOMER;

  const row = (label: string, list: typeof contacts, spend: number | null): FunnelRow => {
    const paid = list.filter(paidOf).length;
    return {
      label,
      leads: list.length,
      contacted: list.filter((c) => c.firstTouchAt || c.lastContactedAt).length,
      onTime: list.filter((c) => c.leadDueAt && c.firstTouchAt && c.firstTouchAt <= c.leadDueAt).length,
      onClock: list.filter((c) => c.leadDueAt).length,
      demos: list.filter((c) => demoed.has(c.id)).length,
      trials: list.filter((c) => c.tenantId).length,
      active: list.filter((c) => active.has(c.id) || paidOf(c)).length,
      paid,
      spend,
      costPerLead: spend != null && list.length ? Math.round(spend / list.length) : null,
      costPerPaid: spend != null && paid ? Math.round(spend / paid) : null,
    };
  };
  const spendFor = (source: string) => {
    const rows = spendRows.filter((s) => s.source.toLowerCase() === source.toLowerCase());
    return rows.length ? rows.reduce((n, s) => n + s.amount, 0) : null;
  };
  const sources = [...new Set(contacts.map((c) => c.source ?? 'Unknown'))];
  const bySource = sources.map((src) => row(src, contacts.filter((c) => (c.source ?? 'Unknown') === src), spendFor(src))).sort((a, b) => b.leads - a.leads);
  // Ad campaigns, whatever form the lead came through (a Meta form, or the website from an ad's link).
  const tagged = contacts.filter((c) => c.firstCampaign);
  const campaignSpend = (name: string) => {
    const rows = spendRows.filter((x) => x.campaign === name);
    return rows.length ? rows.reduce((n, x) => n + x.amount, 0) : null;
  };
  const campaigns = [...new Set(tagged.map((c) => c.firstCampaign!))]
    .map((name) => row(name, tagged.filter((c) => c.firstCampaign === name), campaignSpend(name)))
    .sort((a, b) => b.leads - a.leads);
  const done = shows.find((s) => s.status === CrmDemoStatus.DONE)?._count._all ?? 0;
  const missed = shows.find((s) => s.status === CrmDemoStatus.NO_SHOW)?._count._all ?? 0;
  return {
    from,
    to,
    total: row('All sources', contacts, spendRows.length ? spendRows.reduce((n, s) => n + s.amount, 0) : null),
    bySource,
    byGrade: (['HOT', 'WARM'] as const).map((g) => row(g === 'HOT' ? 'Hot' : 'Warm', contacts.filter((c) => c.leadGrade === g), null)),
    campaigns,
    demos: { done, missed, showUpRate: done + missed ? Math.round((done * 100) / (done + missed)) : null },
    lost: lostRows
      .map((l) => ({ code: l.lostReasonCode ?? 'OTHER', label: LOST_REASONS[(l.lostReasonCode ?? 'OTHER') as keyof typeof LOST_REASONS] ?? l.lostReasonCode ?? 'Other', count: l._count._all }))
      .sort((a, b) => b.count - a.count),
  };
}

/** The weekly email's funnel section (Monday). */
export async function weeklyFunnelLines(now = new Date()) {
  const f30 = await funnel(new Date(now.getTime() - 30 * DAY), now);
  const f7 = await funnel(new Date(now.getTime() - 7 * DAY), now);
  const pct = (a: number, b: number) => (b ? `${Math.round((a * 100) / b)}%` : '—');
  const rupees = (n: number) => `₹${n.toLocaleString('en-IN')}`;
  const sources = f30.bySource.map((r) => ({
    text: `${r.label}: ${r.leads} lead${r.leads === 1 ? '' : 's'}`,
    sub: `${r.contacted} contacted → ${r.demos} demos → ${r.trials} trials → ${r.active} active → ${r.paid} paid`,
    aside: r.costPerLead != null ? `${rupees(r.costPerLead)} a lead${r.costPerPaid != null ? ` · ${rupees(r.costPerPaid)} a paying hostel` : ''}` : null,
  }));
  const habits = [
    { text: `Contacted within 1 working hour: ${pct(f7.total.onTime, f7.total.onClock)}`, sub: `${f7.total.onTime} of ${f7.total.onClock} leads last week` },
    { text: `Demo show-up: ${f7.demos.showUpRate != null ? `${f7.demos.showUpRate}%` : '—'}`, sub: `${f7.demos.done} held, ${f7.demos.missed} missed last week` },
    ...f30.byGrade.map((r) => ({ text: `${r.label} leads: ${r.leads}`, sub: `${r.paid} paid · ${r.trials} trials (last 30 days)` })),
  ];
  const lost = f7.lost.slice(0, 5).map((l) => ({ text: l.label, aside: String(l.count) }));
  return { sources, habits, lost };
}
