import { randomUUID } from 'node:crypto';
import { Role, type BugResolution, type BugStatus } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { emailFailed, sendEmail } from '../../lib/email';
import { ConflictError } from '../../lib/errors';
import { isPlaceholderEmail } from '../../lib/no-login';
import { bugNotificationEmail, crmEmail } from '../../lib/email-templates';
import { publicWebUrl } from '../../config/env';
import { GITHUB_ACTOR, TRACKER_ROLES, type BugActor } from './bug-access';
import { bugKey } from './bug-rules';

/**
 * Telling people what happened on their bugs (docs/bug-tracker-plan.md, BT4).
 *
 * Every event that concerns someone leaves them one BugNotification: the
 * bell's list in the tracker, and one email (D7), unless they switched that
 * group off. The person who did it is never told about their own action, and
 * nothing goes to an account that is switched off.
 *
 * The row is written with the change; the email goes out afterwards, in the
 * background, so a slow mail server never slows the tracker. A bulk change
 * sends each person one email for the lot. The hourly job sweeps up anything
 * a restart left unsent.
 *
 * Nothing here throws to its caller: a notification that fails must not undo
 * or fail the change it is about.
 */

/** The email switches a member has (D7). WEEKLY is the super admin's Monday summary. */
export const NOTIFY_GROUPS = ['ASSIGNED', 'STATUS', 'COMMENT', 'MENTION'] as const;
export type NotifyGroup = (typeof NOTIFY_GROUPS)[number];
export const EMAIL_SWITCHES = [...NOTIFY_GROUPS, 'WEEKLY'] as const;
export type EmailSwitch = (typeof EMAIL_SWITCHES)[number];

export const NOTIFY_KINDS = ['ASSIGNED', 'NEW_ASSIGNED', 'ASKED', 'ANSWERED', 'FIXED', 'DEPLOYED', 'SUGGESTED', 'CLOSED', 'REOPENED', 'COMMENT', 'MENTION'] as const;
export type NotifyKind = (typeof NOTIFY_KINDS)[number];

type Tone = 'info' | 'good' | 'warning' | 'danger' | 'neutral';
const KINDS: Record<NotifyKind, { group: NotifyGroup; label: string; tone: Tone; says: (actor: string, key: string) => string }> = {
  ASSIGNED: { group: 'ASSIGNED', label: 'Assigned to you', tone: 'info', says: (a, k) => `${a} assigned ${k} to you` },
  NEW_ASSIGNED: { group: 'ASSIGNED', label: 'New bug for you', tone: 'info', says: (a, k) => `${a} reported ${k}, and it came to you` },
  ASKED: { group: 'STATUS', label: 'Question', tone: 'warning', says: (a, k) => `${a} asked a question on ${k}` },
  ANSWERED: { group: 'STATUS', label: 'Answered', tone: 'info', says: (a, k) => `${a} answered the question on ${k}` },
  FIXED: { group: 'STATUS', label: 'Fixed', tone: 'good', says: (a, k) => `${a} marked ${k} as fixed` },
  // BT5: the release with the fix went out. The snippet names the release.
  DEPLOYED: { group: 'STATUS', label: 'Ready to verify', tone: 'good', says: (a, k) => `${a} deployed the fix for ${k}` },
  SUGGESTED: { group: 'STATUS', label: 'Close suggested', tone: 'neutral', says: (a, k) => `${a} suggests closing ${k} without a fix` },
  CLOSED: { group: 'STATUS', label: 'Closed', tone: 'good', says: (a, k) => `${a} closed ${k}` },
  REOPENED: { group: 'STATUS', label: 'Reopened', tone: 'danger', says: (a, k) => `${a} reopened ${k}` },
  COMMENT: { group: 'COMMENT', label: 'New comment', tone: 'info', says: (a, k) => `${a} commented on ${k}` },
  MENTION: { group: 'MENTION', label: 'You were mentioned', tone: 'info', says: (a, k) => `${a} mentioned you on ${k}` },
};
const isKind = (k: string): k is NotifyKind => k in KINDS;

const MEMBER_ROLES: Role[] = [Role.SUPER_ADMIN, ...TRACKER_ROLES];
const SNIPPET = 400;

/** Replaceable in tests, so no mail leaves and what would have gone can be read. */
export const mail = { send: sendEmail };

export const bugUrl = (number: number) => `${publicWebUrl}/bugs#bugs/${number}`;
const settingsUrl = () => `${publicWebUrl}/bugs#notifications`;

const STATUS_LABEL: Record<BugStatus, string> = { OPEN: 'Open', IN_PROGRESS: 'In progress', NEEDS_INFO: 'Needs information', FIXED: 'Waiting for QA', REOPENED: 'Reopened', CLOSED: 'Closed' };
const RESOLUTION_LABEL: Record<BugResolution, string> = { VERIFIED: 'Verified fixed', DUPLICATE: 'Duplicate', NOT_A_BUG: 'Not a bug', CANNOT_REPRODUCE: "Can't reproduce", WONT_FIX: "Won't fix" };
export const resolutionLabel = (r: BugResolution) => RESOLUTION_LABEL[r];
const cap = (s: string) => s.charAt(0) + s.slice(1).toLowerCase();

// ── Background sends ────────────────────────────────────────────────────────

const inFlight = new Set<Promise<void>>();
function background(work: () => Promise<void>): void {
  const p = work()
    .catch((err) => {
      // eslint-disable-next-line no-console
      console.error(`[bugs] notification email failed: ${err instanceof Error ? err.message : String(err)}`);
    })
    .finally(() => inFlight.delete(p));
  inFlight.add(p);
}
/** Resolves when every email started so far has been handed over (tests, shutdown). */
export async function settle(): Promise<void> {
  while (inFlight.size) await Promise.all([...inFlight]);
}

// ── Telling people ──────────────────────────────────────────────────────────

export interface Recipient {
  userId: string | null | undefined;
  kind: NotifyKind;
}

/** The people on a bug: who follows it, and who it is assigned to. */
export async function peopleOn(bugId: string, assigneeId: string | null): Promise<string[]> {
  const watchers = await db.bugWatcher.findMany({ where: { bugId }, select: { userId: true } });
  return [...new Set([...watchers.map((w) => w.userId), ...(assigneeId ? [assigneeId] : [])])];
}

/**
 * One notification per person for one event. A person named twice gets the
 * first (so list a mention before a comment). `batchId` holds the emails back
 * for `sendBatch`.
 */
export async function notify(p: { bugId: string; actor: BugActor; to: Recipient[]; snippet?: string | null; batchId?: string }): Promise<void> {
  try {
    const first = new Map<string, NotifyKind>();
    for (const r of p.to) if (r.userId && r.userId !== p.actor.id && !first.has(r.userId)) first.set(r.userId, r.kind);
    if (!first.size) return;
    const ids = [...first.keys()];
    const [users, prefs] = await Promise.all([
      db.user.findMany({ where: { id: { in: ids }, role: { in: MEMBER_ROLES }, deactivatedAt: null }, select: { id: true, email: true } }),
      db.bugNotifyPrefs.findMany({ where: { userId: { in: ids } } }),
    ]);
    if (!users.length) return;
    const off = new Map(prefs.map((x) => [x.userId, new Set(x.emailOff)]));
    const snippet = p.snippet?.trim() ? (p.snippet.trim().length > SNIPPET ? `${p.snippet.trim().slice(0, SNIPPET - 1)}…` : p.snippet.trim()) : null;
    const rows = users.map((u) => {
      const kind = first.get(u.id)!;
      const group = KINDS[kind].group;
      const emailOn = !off.get(u.id)?.has(group) && !isPlaceholderEmail(u.email);
      return { id: randomUUID(), userId: u.id, bugId: p.bugId, actorId: p.actor.id, kind, group, snippet, emailStatus: emailOn ? 'PENDING' : 'NONE', batchId: p.batchId ?? null };
    });
    await db.bugNotification.createMany({ data: rows });
    if (!p.batchId) {
      const pending = rows.filter((r) => r.emailStatus === 'PENDING').map((r) => r.id);
      if (pending.length) background(() => deliver(pending));
    }
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[bugs] could not record a notification: ${err instanceof Error ? err.message : String(err)}`);
  }
}

/** Send what a bulk change held back: one email per person. */
export function sendBatch(batchId: string): void {
  background(() => deliverBatch(batchId));
}

// ── Emails ──────────────────────────────────────────────────────────────────

const withFacts = {
  bug: { select: { number: true, title: true, severity: true, status: true, resolution: true, module: { select: { name: true } } } },
} as const;

async function claim(ids: string[]): Promise<string[]> {
  const mine: string[] = [];
  for (const id of ids) {
    // Only one sender per row: whoever flips it from PENDING has it.
    const got = await db.bugNotification.updateMany({ where: { id, emailStatus: 'PENDING' }, data: { emailStatus: 'SENDING' } });
    if (got.count === 1) mine.push(id);
  }
  return mine;
}

const statusOf = (r: Awaited<ReturnType<typeof sendEmail>>) => (r.mode === 'log' ? 'DRY_RUN' : emailFailed(r) || !r.sent ? 'FAILED' : 'SENT');

async function names(ids: string[]) {
  const rows = await db.user.findMany({ where: { id: { in: [...new Set(ids)] } }, select: { id: true, name: true, email: true, role: true, deactivatedAt: true } });
  const map = new Map(rows.map((r) => [r.id, r]));
  // A move GitHub made with nobody on the team to name (BT6): "GitHub marked BUG-12 as fixed".
  if (ids.includes(GITHUB_ACTOR.id)) map.set(GITHUB_ACTOR.id, { id: GITHUB_ACTOR.id, name: GITHUB_ACTOR.name, email: '', role: GITHUB_ACTOR.role, deactivatedAt: new Date(0) });
  return map;
}

async function deliver(ids: string[]): Promise<void> {
  const mine = await claim(ids);
  if (!mine.length) return;
  const rows = await db.bugNotification.findMany({ where: { id: { in: mine } }, include: withFacts });
  const who = await names(rows.flatMap((r) => [r.userId, r.actorId]));
  for (const n of rows) {
    const to = who.get(n.userId);
    // Switched off (or moved out of the team) since the event: nothing is sent.
    if (!to || to.deactivatedAt || !MEMBER_ROLES.includes(to.role) || !isKind(n.kind)) {
      await db.bugNotification.update({ where: { id: n.id }, data: { emailStatus: 'NONE' } });
      continue;
    }
    const k = KINDS[n.kind];
    const key = bugKey(n.bug.number);
    const message = bugNotificationEmail({
      name: to.name,
      label: k.label,
      tone: k.tone,
      headline: k.says(who.get(n.actorId)?.name ?? 'Someone', key),
      bugKey: key,
      bugTitle: n.bug.title,
      snippet: n.snippet,
      rows: [
        ['Status', n.bug.status === 'CLOSED' && n.bug.resolution ? `Closed · ${RESOLUTION_LABEL[n.bug.resolution].toLowerCase()}` : STATUS_LABEL[n.bug.status]],
        ['Severity', cap(n.bug.severity)],
        ['Module', n.bug.module.name],
      ],
      url: bugUrl(n.bug.number),
      settingsUrl: settingsUrl(),
    });
    let status = 'FAILED';
    try {
      status = statusOf(await mail.send(to.email, message.subject, message.text, message.html));
    } finally {
      await db.bugNotification.update({ where: { id: n.id }, data: { emailStatus: status } });
    }
  }
}

async function deliverBatch(batchId: string): Promise<void> {
  const waiting = await db.bugNotification.findMany({ where: { batchId, emailStatus: 'PENDING' }, select: { id: true, userId: true } });
  const byUser = new Map<string, string[]>();
  for (const w of waiting) byUser.set(w.userId, [...(byUser.get(w.userId) ?? []), w.id]);
  for (const [userId, ids] of byUser) {
    // One bug is an ordinary email; several are one email listing them.
    if (ids.length === 1) {
      await deliver(ids);
      continue;
    }
    const mine = await claim(ids);
    if (!mine.length) continue;
    const rows = await db.bugNotification.findMany({ where: { id: { in: mine } }, include: withFacts, orderBy: { createdAt: 'asc' } });
    const who = await names([userId, ...rows.map((r) => r.actorId)]);
    const to = who.get(userId);
    if (!to || to.deactivatedAt || !MEMBER_ROLES.includes(to.role)) {
      await db.bugNotification.updateMany({ where: { id: { in: mine } }, data: { emailStatus: 'NONE' } });
      continue;
    }
    const actor = who.get(rows[0].actorId)?.name ?? 'Someone';
    const allAssigned = rows.every((r) => r.kind === 'ASSIGNED');
    const allClosed = rows.every((r) => r.kind === 'CLOSED');
    const allDeployed = rows.every((r) => r.kind === 'DEPLOYED');
    const title = allAssigned
      ? `${actor} assigned ${rows.length} bugs to you`
      : allClosed
        ? `${actor} closed ${rows.length} bugs you are on`
        : allDeployed
          ? `${rows[0].snippet ?? 'A release'} is deployed: ${rows.length} fixes are ready to verify`
          : `${actor} changed ${rows.length} bugs you are on`;
    const message = crmEmail({
      title,
      intro: `Hi ${to.name}, ${title} in the HostelCare bug tracker.`,
      badge: 'Bug tracker',
      sections: [
        {
          heading: 'Bugs',
          items: rows.map((r) => ({
            text: `${bugKey(r.bug.number)}  ${r.bug.title}`,
            sub: [cap(r.bug.severity), r.bug.module.name, ...(r.snippet && !allDeployed ? [r.snippet] : [])].join(' · '),
            url: bugUrl(r.bug.number),
            aside: isKind(r.kind) ? KINDS[r.kind].label : null,
          })),
        },
      ],
      cta: { label: 'Open my work', url: `${publicWebUrl}/bugs#work` },
      reason: `You get this because you are on these bugs. To stop these emails, open Notifications in the bug tracker: ${settingsUrl()}`,
      signoff: '— HostelCare bug tracker',
    });
    let status = 'FAILED';
    try {
      status = statusOf(await mail.send(to.email, message.subject, message.text, message.html));
    } finally {
      await db.bugNotification.updateMany({ where: { id: { in: mine } }, data: { emailStatus: status } });
    }
  }
}

/**
 * The job's sweep: emails that a restart left unsent. Anything still waiting
 * after five minutes was not picked up by the request that made it.
 */
export async function sendLeftovers(now = new Date()): Promise<number> {
  const before = new Date(now.getTime() - 5 * 60_000);
  const rows = await db.bugNotification.findMany({ where: { emailStatus: 'PENDING', createdAt: { lt: before } }, select: { id: true, batchId: true }, take: 500, orderBy: { createdAt: 'asc' } });
  const singles = rows.filter((r) => !r.batchId).map((r) => r.id);
  if (singles.length) await deliver(singles);
  for (const batchId of new Set(rows.map((r) => r.batchId).filter((b): b is string => !!b))) await deliverBatch(batchId);
  return rows.length;
}

// ── The bell ────────────────────────────────────────────────────────────────

export async function unreadCount(actor: BugActor): Promise<number> {
  return db.bugNotification.count({ where: { userId: actor.id, readAt: null } });
}

export async function listNotifications(actor: BugActor, f: { page: number; limit: number; unread: boolean }) {
  const where = { userId: actor.id, ...(f.unread ? { readAt: null } : {}) };
  const [rows, total, unread] = await Promise.all([
    db.bugNotification.findMany({ where, include: withFacts, orderBy: { createdAt: 'desc' }, skip: (f.page - 1) * f.limit, take: f.limit }),
    db.bugNotification.count({ where }),
    unreadCount(actor),
  ]);
  const who = await names(rows.map((r) => r.actorId));
  return {
    items: rows.map((n) => {
      const key = bugKey(n.bug.number);
      const actorName = who.get(n.actorId)?.name ?? 'Someone';
      return {
        id: n.id,
        kind: n.kind,
        label: isKind(n.kind) ? KINDS[n.kind].label : 'Update',
        text: isKind(n.kind) ? KINDS[n.kind].says(actorName, key) : `${actorName} changed ${key}`,
        snippet: n.snippet,
        bug: { number: n.bug.number, key, title: n.bug.title, status: n.bug.status, resolution: n.bug.resolution },
        actor: { id: n.actorId, name: actorName },
        read: !!n.readAt,
        createdAt: n.createdAt,
      };
    }),
    total,
    page: f.page,
    limit: f.limit,
    hasMore: (f.page - 1) * f.limit + rows.length < total,
    unread,
  };
}

/** Mark as read: the ones named, or all of mine. Returns how many are still unread. */
export async function markRead(actor: BugActor, p: { ids?: string[]; all?: boolean }) {
  await db.bugNotification.updateMany({ where: { userId: actor.id, readAt: null, ...(p.all ? {} : { id: { in: p.ids ?? [] } }) }, data: { readAt: new Date() } });
  return { unread: await unreadCount(actor) };
}

/** Opening a bug reads what I was told about it. */
export async function markBugRead(actor: BugActor, bugId: string): Promise<void> {
  await db.bugNotification.updateMany({ where: { userId: actor.id, bugId, readAt: null }, data: { readAt: new Date() } });
}

// ── A member's email switches ───────────────────────────────────────────────

const switchesFor = (actor: BugActor): readonly EmailSwitch[] => (actor.role === Role.SUPER_ADMIN ? EMAIL_SWITCHES : NOTIFY_GROUPS);

export async function getPrefs(actor: BugActor) {
  const row = await db.bugNotifyPrefs.findUnique({ where: { userId: actor.id } });
  const off = new Set(row?.emailOff ?? []);
  const me = await db.user.findUnique({ where: { id: actor.id }, select: { email: true } });
  return { email: me?.email ?? '', switches: switchesFor(actor).map((key) => ({ key, on: !off.has(key) })), githubLogin: row?.githubLogin ?? null };
}

/**
 * BT6: my GitHub username, so a commit or pull request of mine that fixes a
 * bug is credited to me here. One member per username.
 */
export async function setGithubLogin(actor: BugActor, login: string | null) {
  const value = login ? login.toLowerCase() : null;
  if (value) {
    const taken = await db.bugNotifyPrefs.findFirst({ where: { githubLogin: value, userId: { not: actor.id } }, select: { userId: true } });
    if (taken) throw new ConflictError('Another member already uses that GitHub username.', 'GITHUB_LOGIN_TAKEN');
  }
  await db.bugNotifyPrefs.upsert({ where: { userId: actor.id }, create: { userId: actor.id, githubLogin: value }, update: { githubLogin: value } });
  return getPrefs(actor);
}

export async function setPrefs(actor: BugActor, emailOff: EmailSwitch[]) {
  const allowed = new Set<string>(switchesFor(actor));
  const off = [...new Set(emailOff)].filter((k) => allowed.has(k));
  await db.bugNotifyPrefs.upsert({ where: { userId: actor.id }, create: { userId: actor.id, emailOff: off }, update: { emailOff: off } });
  return getPrefs(actor);
}
