import { env } from "./env";
import { emailTemplate, sendEmail } from "./mailer";
import { prisma } from "./prisma";

/**
 * Portal ticket emails (2026-11-13): tells the requester and/or chosen addresses when a portal ticket gets a
 * comment, a reply or an attachment ("updated"), and when it is moved to the closing list ("resolved", with the
 * latest comment as the closing note). Configured per board in Portal settings; off unless enabled there.
 *
 * Updates are collected per ticket for UPDATE_DELAY_MS, so a comment with a pasted screenshot (attachment +
 * comment) or a quick back-and-forth becomes one email instead of several.
 */
export type PortalTicketEmailSettings = {
  onUpdate: boolean;
  onClose: boolean;
  toRequester: boolean;
  emails: string[];
  closeListId: string | null;
  includeCommentText: boolean;
};

export const DEFAULT_PORTAL_TICKET_EMAILS: PortalTicketEmailSettings = {
  onUpdate: false,
  onClose: false,
  toRequester: true,
  emails: [],
  closeListId: null,
  includeCommentText: true,
};

export function parsePortalTicketEmails(value: unknown): PortalTicketEmailSettings {
  const v = value && typeof value === "object" ? (value as Record<string, unknown>) : {};
  return {
    onUpdate: v.onUpdate === true,
    onClose: v.onClose === true,
    toRequester: v.toRequester !== false,
    emails: Array.isArray(v.emails) ? v.emails.filter((e): e is string => typeof e === "string") : [],
    closeListId: typeof v.closeListId === "string" && v.closeListId ? v.closeListId : null,
    includeCommentText: v.includeCommentText !== false,
  };
}

const UPDATE_DELAY_MS = 60_000;

type UpdateEvent =
  | { kind: "comment"; actorId: string | null; commentId: string; isReply: boolean }
  | { kind: "attachment"; actorId: string | null; filename: string };

const pending = new Map<string, { events: UpdateEvent[]; timer: NodeJS.Timeout }>();

function escapeHtml(text: string): string {
  return text
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

/** Comment markdown -> short plain text for an email (images and link targets dropped). */
function commentText(body: string, max = 1500): string {
  const plain = body
    .replace(/!\[[^\]]*\]\([^)]*\)/g, "")
    .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
    .replace(/<[^>]+>/g, " ")
    .replace(/\*\*|__/g, "")
    .replace(/[ \t]+/g, " ")
    .replace(/\n{3,}/g, "\n\n")
    .trim();
  return plain.length > max ? plain.slice(0, max) + "…" : plain;
}

async function loadTicket(cardId: string) {
  const card = await prisma.card.findUnique({
    where: { id: cardId },
    select: {
      id: true,
      title: true,
      boardId: true,
      listId: true,
      portalRequestTypeId: true,
      submitterEmail: true,
      submitterName: true,
      guestTrackingToken: true,
      list: { select: { board: { select: { id: true, name: true, portalEnabled: true, portalTitle: true, portalTicketEmails: true } } } },
    },
  });
  if (!card || !card.portalRequestTypeId) return null;
  const board = card.list.board;
  // the ticket must still be on its portal board (not moved to another board)
  if (!board.portalEnabled || board.id !== card.boardId) return null;
  return { card, board, settings: parsePortalTicketEmails(board.portalTicketEmails) };
}

type Ticket = NonNullable<Awaited<ReturnType<typeof loadTicket>>>;

/** Who gets the email, each with the link that works for them; people who did everything in it are left out. */
async function recipients(ticket: Ticket, actorIds: (string | null)[]) {
  const { card, settings } = ticket;
  const actors = await prisma.user.findMany({
    where: { id: { in: actorIds.filter((a): a is string => !!a) } },
    select: { email: true },
  });
  const allByOne = actorIds.length > 0 && actorIds.every((a) => a && a === actorIds[0]);
  const skip = new Set(allByOne ? actors.map((a) => a.email.toLowerCase()) : []);
  const boardUrl = `${env.CLIENT_URL}/boards/${card.boardId}?card=${card.id}`;
  const out = new Map<string, { url: string; label: string; isRequester: boolean }>();
  if (settings.toRequester && card.submitterEmail) {
    const email = card.submitterEmail.toLowerCase();
    out.set(email, card.guestTrackingToken
      ? { url: `${env.CLIENT_URL}/track/${card.guestTrackingToken}`, label: "View my request", isRequester: true }
      : { url: boardUrl, label: "View my request", isRequester: true });
  }
  for (const e of settings.emails) {
    const email = e.toLowerCase();
    if (!out.has(email)) out.set(email, { url: boardUrl, label: "Open ticket in My Assisto", isRequester: false });
  }
  for (const s of skip) out.delete(s);
  return out;
}

function portalName(ticket: Ticket) {
  return ticket.board.portalTitle || ticket.board.name;
}

function queueUpdate(cardId: string, event: UpdateEvent) {
  const existing = pending.get(cardId);
  if (existing) {
    existing.events.push(event);
    return;
  }
  const timer = setTimeout(() => {
    const entry = pending.get(cardId);
    pending.delete(cardId);
    if (entry) flushUpdate(cardId, entry.events).catch((err) => console.error("[portal-mail] update email failed:", err));
  }, UPDATE_DELAY_MS);
  pending.set(cardId, { events: [event], timer });
}

async function flushUpdate(cardId: string, events: UpdateEvent[]) {
  const ticket = await loadTicket(cardId);
  if (!ticket || !ticket.settings.onUpdate) return;
  const { card, settings } = ticket;

  const commentIds = events.filter((e) => e.kind === "comment").map((e) => (e as { commentId: string }).commentId);
  const comments = commentIds.length
    ? await prisma.comment.findMany({
        where: { id: { in: commentIds }, cardId },
        select: { id: true, bodyHtml: true, audioUrl: true, author: { select: { name: true } } },
      })
    : [];
  const actorNames = new Map(
    (await prisma.user.findMany({
      where: { id: { in: events.map((e) => e.actorId).filter((a): a is string => !!a) } },
      select: { id: true, name: true },
    })).map((u) => [u.id, u.name])
  );

  const items: string[] = [];
  for (const e of events) {
    const who = escapeHtml((e.actorId && actorNames.get(e.actorId)) || "Someone");
    if (e.kind === "attachment") {
      items.push(`<li style="margin: 0 0 10px;"><strong>${who}</strong> added an attachment: ${escapeHtml(e.filename)}</li>`);
      continue;
    }
    const c = comments.find((x) => x.id === e.commentId);
    if (!c) continue; // deleted before the email went out
    const text = settings.includeCommentText ? commentText(c.bodyHtml) : "";
    const body = text
      ? `<div style="margin-top: 4px; padding: 10px 12px; background: #f5f5f7; border-radius: 8px; color: #17171c; white-space: pre-wrap;">${escapeHtml(text)}</div>`
      : c.audioUrl && settings.includeCommentText ? `<div style="margin-top: 4px; color: #8a8a94;">(voice note)</div>` : "";
    items.push(`<li style="margin: 0 0 10px;"><strong>${who}</strong> ${e.isReply ? "replied" : "commented"}${body}</li>`);
  }
  if (!items.length) return;

  const to = await recipients(ticket, events.map((e) => e.actorId));
  const name = portalName(ticket);
  for (const [email, r] of to) {
    const html = emailTemplate({
      title: `Update on: ${escapeHtml(card.title)}`,
      bodyHtml: `${r.isRequester && card.submitterName ? `Hi ${escapeHtml(card.submitterName)},<br/><br/>` : ""}There is an update on the request "<strong>${escapeHtml(card.title)}</strong>" on ${escapeHtml(name)}.<br/><br/>
        <ul style="margin: 0; padding-left: 18px;">${items.join("")}</ul>`,
      ctaLabel: r.label,
      ctaUrl: r.url,
    });
    sendEmail({ to: email, subject: `[${name}] Updated: "${card.title}"`, html }).catch((err) =>
      console.error(`[portal-mail] failed to send update email to ${email}:`, err)
    );
  }
}

/** A comment or reply was written on a card (any card; only portal tickets with the setting on send mail). */
export function portalTicketCommented(cardId: string, commentId: string, actorId: string | null, isReply: boolean) {
  queueUpdate(cardId, { kind: "comment", actorId, commentId, isReply });
}

/** An attachment was added to a card. */
export function portalTicketAttachmentAdded(cardId: string, filename: string, actorId: string | null) {
  queueUpdate(cardId, { kind: "attachment", actorId, filename });
}

function isDoneLikeName(name: string) {
  return /^(done|completed?|closed|resolved|finished)$/i.test(name.trim());
}

/** A card was moved to a list; sends the "resolved" email when that is the ticket's closing list. */
export async function portalTicketMoved(cardId: string, listId: string, actorId: string | null) {
  const ticket = await loadTicket(cardId);
  if (!ticket || !ticket.settings.onClose) return;
  const { card, settings } = ticket;
  if (card.listId !== listId) return; // a linked copy moved on another board, not the ticket itself
  const list = await prisma.list.findUnique({ where: { id: listId }, select: { name: true, boardId: true } });
  if (!list || list.boardId !== card.boardId) return;
  const isClose = settings.closeListId ? settings.closeListId === listId : isDoneLikeName(list.name);
  if (!isClose) return;

  // the closing email replaces any update email still waiting for this ticket
  const waiting = pending.get(cardId);
  if (waiting) {
    clearTimeout(waiting.timer);
    pending.delete(cardId);
  }

  // closing note: the latest comment (written before the close), when comment text may be shared
  let note = "";
  let noteBy = "";
  if (settings.includeCommentText) {
    const last = await prisma.comment.findFirst({
      where: { cardId },
      orderBy: { createdAt: "desc" },
      select: { bodyHtml: true, author: { select: { name: true } } },
    });
    if (last) {
      note = commentText(last.bodyHtml);
      noteBy = last.author.name;
    }
  }

  const to = await recipients(ticket, [actorId]);
  const name = portalName(ticket);
  for (const [email, r] of to) {
    const html = emailTemplate({
      title: `Resolved: ${escapeHtml(card.title)}`,
      bodyHtml: `${r.isRequester && card.submitterName ? `Hi ${escapeHtml(card.submitterName)},<br/><br/>` : ""}The request "<strong>${escapeHtml(card.title)}</strong>" on ${escapeHtml(name)} has been resolved and closed.
        ${note ? `<div style="margin-top: 14px; color: #8a8a94; font-size: 13px;">Closing note${noteBy ? ` from ${escapeHtml(noteBy)}` : ""}</div><div style="margin-top: 4px; padding: 10px 12px; background: #f5f5f7; border-radius: 8px; color: #17171c; white-space: pre-wrap;">${escapeHtml(note)}</div>` : ""}`,
      ctaLabel: r.label,
      ctaUrl: r.url,
    });
    sendEmail({ to: email, subject: `[${name}] Resolved: "${card.title}"`, html }).catch((err) =>
      console.error(`[portal-mail] failed to send resolved email to ${email}:`, err)
    );
  }
}
