import { randomUUID } from 'node:crypto';
import { prismaUnscoped } from '../../lib/prisma';
import { crmEmail } from '../../lib/email-templates';
import { getCrmSettings, superAdminCopyAddress } from './crm-settings.service';
import { crmMembersWithPrefs, deliver, fmtIstTime, manageUrl } from './crm-mail';
import type { Actor } from './crm-users.service';

/**
 * Activity alerts: "Ravi moved DEAL-0004 to Negotiation".
 *
 * Who hears about a change: the person it is about (the contact's owner, the
 * deal's assignee, a task's new assignee) and everyone who asked for all
 * activity — never the person who made it. The super admin gets a copy.
 *
 * So nobody is flooded, a change is not mailed on its own: it joins the
 * recipient's open batch, and the batch leaves as one email ten minutes
 * after its first line (see flushAlerts, run by the CRM tick).
 *
 * The super admin's copies of follow-up and task reminders join the same
 * batch (as "reminder" lines), so the copy of a whole morning's reminders to
 * the team is one email, not one per person (10 Oct 2026).
 */

export const ALERT_WINDOW_MS = 10 * 60 * 1000;

interface Line {
  at: string;
  text: string;
  url: string | null;
  /** 'reminder': a copy of a reminder sent to a team member. Absent: an activity line. */
  kind?: 'reminder';
}

export interface CrmEvent {
  actor: Actor;
  /** One sentence, actor first: "Ravi Kumar won DEAL-0004 · Green PG (₹64,800)". */
  text: string;
  url?: string | null;
  /** The people this change is about (owner, assignee). */
  about: (string | null | undefined)[];
}

/** Queue an alert. Fire-and-forget: a mail problem never fails the action. */
export function notify(e: CrmEvent, now = new Date()) {
  void enqueue(e, now).catch((err) => {
    // eslint-disable-next-line no-console
    console.error(`[crm] alert not queued: ${err instanceof Error ? err.message : String(err)}`);
  });
}

async function addLine(p: { pendingKey: string; userId: string | null; toEmail: string; toName: string; isCopy: boolean; line: Line; now: Date }) {
  const lines = JSON.stringify([p.line]);
  // One open batch per recipient; append to it, or open one. Prisma stores
  // timestamps as UTC without a zone; raw SQL must too, whatever the
  // database session's time zone is.
  await prismaUnscoped.$executeRaw`
    INSERT INTO "CrmAlertBatch" ("id", "pendingKey", "userId", "toEmail", "toName", "isCopy", "lines", "firstAt", "sendAfter")
    VALUES (${randomUUID()}, ${p.pendingKey}, ${p.userId}, ${p.toEmail}, ${p.toName}, ${p.isCopy}, ${lines}::jsonb,
            (${p.now.toISOString()}::timestamptz AT TIME ZONE 'UTC'), (${new Date(p.now.getTime() + ALERT_WINDOW_MS).toISOString()}::timestamptz AT TIME ZONE 'UTC'))
    ON CONFLICT ("pendingKey") DO UPDATE SET "lines" = "CrmAlertBatch"."lines" || EXCLUDED."lines"`;
}

export async function enqueue(e: CrmEvent, now = new Date()) {
  const settings = await getCrmSettings();
  if (!settings.emailsEnabled) return;
  const members = await crmMembersWithPrefs();
  const about = new Set(e.about.filter((x): x is string => !!x));
  const targets = members.filter((m) => m.id !== e.actor.id && ((about.has(m.id) && m.prefs.alerts) || m.prefs.allActivity));
  const line: Line = { at: now.toISOString(), text: e.text, url: e.url ?? null };
  for (const m of targets) {
    await addLine({ pendingKey: `u:${m.id}`, userId: m.id, toEmail: m.email, toName: m.name, isCopy: false, line, now });
  }
  const copy = await superAdminCopyAddress({ actorEmail: e.actor.email, recipients: targets.map((t) => t.email) });
  if (copy) await addLine({ pendingKey: `c:${copy}`, userId: null, toEmail: copy, toName: 'Super admin', isCopy: true, line, now });
}

/** Add a reminder copy to the super admin's open batch. */
export async function queueReminderCopy(copyEmail: string, line: { text: string; url: string | null }, now = new Date()) {
  await addLine({ pendingKey: `c:${copyEmail}`, userId: null, toEmail: copyEmail, toName: 'Super admin', isCopy: true, line: { at: now.toISOString(), text: line.text, url: line.url, kind: 'reminder' }, now });
}

/** Send every batch whose ten minutes are up. Returns how many emails went out. */
export async function flushAlerts(now = new Date()) {
  const due = await prismaUnscoped.crmAlertBatch.findMany({ where: { sentAt: null, sendAfter: { lte: now } }, take: 200 });
  let sent = 0;
  for (const b of due) {
    // Close the batch first, so a new change starts a fresh one.
    const claimed = await prismaUnscoped.crmAlertBatch.updateMany({ where: { id: b.id, sentAt: null }, data: { sentAt: now, pendingKey: null } });
    if (claimed.count !== 1) continue;
    const lines = (b.lines as unknown as Line[]) ?? [];
    if (!lines.length) continue;
    const reminders = lines.filter((l) => l.kind === 'reminder');
    const activity = lines.filter((l) => l.kind !== 'reminder');
    const section = (heading: string, list: Line[]) => {
      const shown = list.slice(0, 40);
      return {
        heading: list.length === 1 ? heading : `${heading} (${list.length})`,
        items: [
          ...shown.map((l) => ({ text: l.text, url: l.url, aside: fmtIstTime(new Date(l.at)) })),
          ...(list.length > shown.length ? [{ text: `and ${list.length - shown.length} more`, url: null }] : []),
        ],
      };
    };
    const title =
      lines.length === 1
        ? lines[0].text
        : !activity.length
          ? `${reminders.length} reminders sent to the team`
          : reminders.length
            ? `${activity.length} update${activity.length === 1 ? '' : 's'} and ${reminders.length} reminder${reminders.length === 1 ? '' : 's'} in the CRM`
            : `${lines.length} updates in the CRM`;
    const mail = crmEmail({
      title,
      intro: b.isCopy ? (reminders.length && !activity.length ? 'The reminders the CRM sent to the team in the last few minutes, in one email.' : 'What the team changed in the CRM, and the reminders it sent, in the last few minutes.') : `${b.toName}, here is what changed on your contacts and deals.`,
      badge: reminders.length && !activity.length ? 'Reminders' : 'CRM activity',
      sections: [...(reminders.length ? [section('Reminders sent', reminders)] : []), ...(activity.length ? [section('What happened', activity)] : [])],
      reason: b.isCopy ? 'You get this copy because CRM emails are copied to the super admin. Change it in CRM settings.' : 'You get these because the changes are on your records. Choose what you get in your CRM profile.',
      cta: b.isCopy ? undefined : { label: 'Manage notifications', url: manageUrl() },
    });
    const status = await deliver({ key: `alerts:${b.id}`, kind: 'ALERTS', to: b.toEmail, userId: b.userId, mail, isCopy: b.isCopy });
    if (status === 'SENT' || status === 'DRY_RUN') sent++;
  }
  return sent;
}
