import { BugLinkKind, BugResolution, BugStatus, Prisma, Role, type Bug } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { GITHUB_ACTOR, type BugActor } from './bug-access';
import { canEdit, getBug, loadByNumber, people, READY_TO_VERIFY, summary, WAITING_FOR_RELEASE, whereOf, withModule } from './bug-bugs.service';
import { usableRelease } from './bug-releases.service';
import { randomUUID } from 'node:crypto';
import { allowedActions, bugKey, type BulkInput, type ListBugsInput, type MoveInput } from './bug-rules';
import { notify, peopleOn, resolutionLabel, sendBatch, type NotifyKind } from './bug-notify.service';

/**
 * The fix-and-verify loop (docs/bug-tracker-plan.md, BT3): moving a bug from
 * one status to the next, assigning it, and the lists each person works from.
 *
 * Who may do which move is `allowedActions` (bug-rules.ts), checked here on
 * every move. Each move records a STATUS event with what it needed (the fix
 * note, the question, the reason), so the bug's thread tells the whole story.
 */

const STATUS_WORDS: Record<BugStatus, string> = {
  OPEN: 'open',
  IN_PROGRESS: 'in progress',
  NEEDS_INFO: 'waiting for information',
  FIXED: 'waiting for QA',
  REOPENED: 'reopened',
  CLOSED: 'closed',
};

async function assertOriginal(bug: Bug, duplicateOf: number | undefined): Promise<Bug> {
  if (!duplicateOf) throw new BadRequestError('Say which bug this is a duplicate of.', 'DUPLICATE_OF_REQUIRED');
  if (duplicateOf === bug.number) throw new BadRequestError('A bug cannot be a duplicate of itself.', 'SAME_BUG');
  const original = await db.bug.findUnique({ where: { number: duplicateOf } });
  if (!original) throw new NotFoundError(`${bugKey(duplicateOf)} was not found.`);
  // Two bugs pointing at each other would leave neither as the one to fix.
  const back = await db.bugLink.findFirst({ where: { fromId: original.id, toId: bug.id, kind: BugLinkKind.DUPLICATE } });
  if (back) throw new ConflictError(`${bugKey(duplicateOf)} is already marked as a duplicate of this bug.`, 'DUPLICATE_LOOP');
  return original;
}

/** What the people on a bug are told about each move. Starting work is not news worth an email. */
const NEWS: Partial<Record<MoveInput['action'], NotifyKind>> = { ask: 'ASKED', answer: 'ANSWERED', fix: 'FIXED', suggest: 'SUGGESTED', close: 'CLOSED', reopen: 'REOPENED' };

/** One move. Returns the bug as it now is. `batchId` (a bulk change) holds its emails back to go as one. */
export async function moveBug(number: number, input: MoveInput, actor: BugActor, opts: { batchId?: string } = {}) {
  const bug = await loadByNumber(number);
  if (!allowedActions(actor, bug).includes(input.action)) {
    throw new ForbiddenError(
      bug.status === BugStatus.CLOSED && input.action !== 'reopen'
        ? 'This bug is closed. QA or the super admin can reopen it.'
        : input.action === 'close' || input.action === 'reopen'
          ? 'Only QA or the super admin can close or reopen a bug.'
          : `That can't be done while the bug is ${STATUS_WORDS[bug.status]}, or not by your role.`,
    );
  }

  const now = new Date();
  const data: Prisma.BugUncheckedUpdateInput = { statusChangedAt: now, lastActivityAt: now };
  const changes: Record<string, unknown> = {};
  const after: (tx: Prisma.TransactionClient) => Promise<unknown> = async () => undefined;
  let afterTx = after;
  // A developer who starts a bug takes it; one who fixes an unassigned bug owns the fix.
  const takeIt = (always: boolean) => {
    if (actor.role === Role.DEVELOPER && bug.assigneeId !== actor.id && (always || !bug.assigneeId)) {
      data.assigneeId = actor.id;
      changes.assignee = { from: bug.assigneeId, to: actor.id };
    }
  };
  const dropDuplicateLink = (tx: Prisma.TransactionClient) => tx.bugLink.deleteMany({ where: { fromId: bug.id, kind: BugLinkKind.DUPLICATE } });
  const linkDuplicate = (originalId: string) => async (tx: Prisma.TransactionClient) => {
    await dropDuplicateLink(tx);
    await tx.bugLink.create({ data: { fromId: bug.id, toId: originalId, kind: BugLinkKind.DUPLICATE, createdById: actor.id } });
  };

  let to: BugStatus;
  switch (input.action) {
    case 'start':
      to = BugStatus.IN_PROGRESS;
      takeIt(true);
      break;
    case 'ask':
      to = BugStatus.NEEDS_INFO;
      changes.note = input.note;
      break;
    case 'answer':
      to = BugStatus.OPEN;
      changes.note = input.note;
      break;
    case 'fix': {
      to = BugStatus.FIXED;
      // BT5: a release from the list names where the fix is; otherwise whatever was typed.
      const release = input.fixedInReleaseId ? await usableRelease(input.fixedInReleaseId, bug.app, 'fix') : null;
      const fixedIn = release?.name ?? input.fixedIn ?? null;
      data.resolution = null;
      data.fixNote = input.note;
      data.fixLink = input.fixLink ?? null;
      data.fixedIn = fixedIn;
      data.fixedInReleaseId = release?.id ?? null;
      changes.note = input.note;
      if (input.fixLink) changes.fixLink = input.fixLink;
      if (fixedIn) changes.fixedIn = fixedIn;
      if (release) changes.deployed = !!release.deployedAt;
      takeIt(false);
      afterTx = dropDuplicateLink;
      break;
    }
    case 'suggest': {
      to = BugStatus.FIXED;
      data.resolution = input.resolution;
      changes.suggested = input.resolution;
      changes.note = input.note;
      if (input.resolution === 'DUPLICATE') {
        const original = await assertOriginal(bug, input.duplicateOf);
        changes.duplicateOf = bugKey(original.number);
        afterTx = linkDuplicate(original.id);
      } else afterTx = dropDuplicateLink;
      takeIt(false);
      break;
    }
    case 'close': {
      to = BugStatus.CLOSED;
      // From FIXED with no reason given: QA agrees with what the developer said
      // (a fix → verified; a suggested reason → that reason).
      const resolution: BugResolution | null = input.resolution ?? (bug.status === BugStatus.FIXED ? (bug.resolution ?? BugResolution.VERIFIED) : null);
      if (!resolution) throw new BadRequestError('Say why it is being closed: duplicate, not a bug, can’t reproduce or won’t fix.', 'REASON_REQUIRED');
      if (input.resolution === 'DUPLICATE' || (resolution === 'DUPLICATE' && input.duplicateOf)) {
        const original = await assertOriginal(bug, input.duplicateOf);
        changes.duplicateOf = bugKey(original.number);
        afterTx = linkDuplicate(original.id);
      } else if (resolution !== 'DUPLICATE') afterTx = dropDuplicateLink;
      data.resolution = resolution;
      data.closedAt = now;
      changes.resolution = resolution;
      if (input.note) changes.note = input.note;
      break;
    }
    case 'reopen':
      to = BugStatus.REOPENED;
      data.resolution = null;
      data.closedAt = null;
      data.reopenCount = { increment: 1 };
      changes.note = input.note;
      afterTx = dropDuplicateLink;
      break;
  }
  data.status = to;

  await db.$transaction(async (tx) => {
    // Only if nobody moved it first: two people pressing a button at once get one move.
    const moved = await tx.bug.updateMany({ where: { id: bug.id, status: bug.status }, data });
    if (moved.count !== 1) throw new ConflictError('Someone else just changed this bug. Reload it and try again.', 'BUG_CHANGED');
    await afterTx(tx);
    await tx.bugEvent.create({
      data: { bugId: bug.id, actorId: actor.id, type: 'STATUS', changes: { action: input.action, status: { from: bug.status, to }, ...changes } as Prisma.InputJsonObject },
    });
    // GitHub (BT6) is not a person: it follows nothing.
    const followers = [...(actor.id === GITHUB_ACTOR.id ? [] : [actor.id]), ...(typeof data.assigneeId === 'string' ? [data.assigneeId] : [])];
    await tx.bugWatcher.createMany({ data: followers.map((userId) => ({ bugId: bug.id, userId })), skipDuplicates: true });
  });

  const news = NEWS[input.action];
  if (news) {
    const assigneeNow = typeof data.assigneeId === 'string' ? data.assigneeId : bug.assigneeId;
    const reason = input.action === 'suggest' ? input.resolution : input.action === 'close' ? (data.resolution as BugResolution) : null;
    const said = [reason ? resolutionLabel(reason) + (changes.duplicateOf ? ` of ${String(changes.duplicateOf)}` : '') : null, 'note' in input ? input.note : null].filter(Boolean).join(': ');
    await notify({ bugId: bug.id, actor, to: (await peopleOn(bug.id, assigneeNow)).map((userId) => ({ userId, kind: news })), snippet: said || null, batchId: opts.batchId });
  }
  return getBug(number, actor);
}

// ── Assignment ──────────────────────────────────────────────────────────────

async function assertDeveloper(id: string) {
  const u = await db.user.findFirst({ where: { id, role: Role.DEVELOPER, deactivatedAt: null }, select: { id: true } });
  if (!u) throw new BadRequestError('Choose a developer whose account is switched on.', 'NOT_A_DEVELOPER');
}

/** Give a bug to a developer, or to nobody. Anyone on the tracker, on a bug that isn't closed. */
async function assign(bug: Bug, assigneeId: string | null, actor: BugActor, batchId?: string): Promise<boolean> {
  if (bug.status === BugStatus.CLOSED) throw new ConflictError('This bug is closed. Reopen it to assign it.', 'BUG_CLOSED');
  if (assigneeId === bug.assigneeId) return false;
  if (assigneeId) await assertDeveloper(assigneeId);
  await db.$transaction([
    db.bug.update({ where: { id: bug.id }, data: { assigneeId, lastActivityAt: new Date() } }),
    db.bugEvent.create({ data: { bugId: bug.id, actorId: actor.id, type: 'ASSIGNED', changes: { assignee: { from: bug.assigneeId, to: assigneeId } } } }),
    ...(assigneeId ? [db.bugWatcher.createMany({ data: [{ bugId: bug.id, userId: assigneeId }], skipDuplicates: true })] : []),
  ]);
  if (assigneeId) await notify({ bugId: bug.id, actor, to: [{ userId: assigneeId, kind: 'ASSIGNED' }], batchId });
  return true;
}

export async function assignBug(number: number, assigneeId: string | null, actor: BugActor) {
  await assign(await loadByNumber(number), assigneeId, actor);
  return getBug(number, actor);
}

// ── Several bugs at once ────────────────────────────────────────────────────

/** The same rules as one at a time; each bug succeeds or says why it didn't. */
export async function bulk(input: BulkInput, actor: BugActor) {
  const numbers = [...new Set(input.numbers)];
  const done: number[] = [];
  const failed: { number: number; key: string; message: string }[] = [];
  // One email per person for the whole change, not one per bug.
  const batchId = randomUUID();
  for (const number of numbers) {
    try {
      const bug = await loadByNumber(number);
      if (input.action === 'assign') {
        await assign(bug, input.assigneeId, actor, batchId);
      } else if (input.action === 'priority') {
        if (!canEdit(actor, bug)) throw new ForbiddenError('This bug is closed, so only its reporter, a developer or the super admin can change it.');
        if (bug.priority !== input.priority) {
          await db.$transaction([
            db.bug.update({ where: { id: bug.id }, data: { priority: input.priority, lastActivityAt: new Date() } }),
            db.bugEvent.create({ data: { bugId: bug.id, actorId: actor.id, type: 'EDITED', changes: { priority: { from: bug.priority, to: input.priority } } } }),
          ]);
        }
      } else {
        await moveBug(number, { action: 'close', resolution: 'DUPLICATE', duplicateOf: input.duplicateOf }, actor, { batchId });
      }
      done.push(number);
    } catch (e) {
      failed.push({ number, key: bugKey(number), message: e instanceof Error ? e.message : 'Could not be changed' });
    }
  }
  sendBatch(batchId);
  return { done, failed };
}

// ── My work ─────────────────────────────────────────────────────────────────

const OPEN_WORK: BugStatus[] = [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.REOPENED];

interface WorkGroup {
  key: string;
  title: string;
  hint: string;
  /** The same view on the bug list, as its filters. */
  filters: Record<string, string>;
  where: Prisma.BugWhereInput;
  /** Counts towards the number beside "My work": something for this person to do. */
  attention: boolean;
}

/** What each role works from. The order is the order on the page. */
function groupsFor(actor: BugActor): WorkGroup[] {
  const me = actor.id;
  const csv = (l: BugStatus[]) => l.join(',');
  const dev: WorkGroup[] = [
    { key: 'reopened', title: 'Reopened', hint: 'QA says these are still broken', filters: { assigneeId: me, status: 'REOPENED' }, where: { assigneeId: me, status: BugStatus.REOPENED }, attention: true },
    { key: 'assigned', title: 'Assigned to me', hint: 'Open or in progress', filters: { assigneeId: me, status: csv([BugStatus.OPEN, BugStatus.IN_PROGRESS]) }, where: { assigneeId: me, status: { in: [BugStatus.OPEN, BugStatus.IN_PROGRESS] } }, attention: true },
    { key: 'waiting', title: 'Waiting for an answer', hint: 'You asked the reporter something', filters: { assigneeId: me, status: 'NEEDS_INFO' }, where: { assigneeId: me, status: BugStatus.NEEDS_INFO }, attention: false },
    { key: 'unassigned', title: 'Unassigned', hint: 'Open bugs nobody has taken', filters: { assigneeId: 'none', status: csv(OPEN_WORK) }, where: { assigneeId: null, status: { in: OPEN_WORK } }, attention: false },
    { key: 'for-qa', title: 'My fixes waiting for QA', hint: 'Not yet verified', filters: { assigneeId: me, status: 'FIXED' }, where: { assigneeId: me, status: BugStatus.FIXED }, attention: false },
  ];
  const qa: WorkGroup[] = [
    // BT5: a fix in a release that has not gone out can't be tested yet, so it waits in its own list.
    { key: 'to-verify', title: 'Ready to verify', hint: 'Fixed, or a reason suggested: verify and close, or reopen', filters: { status: 'FIXED', deploy: 'ready' }, where: READY_TO_VERIFY, attention: true },
    { key: 'not-deployed', title: 'Fixed, not deployed yet', hint: 'The fix is in a release that has not gone out', filters: { status: 'FIXED', deploy: 'waiting' }, where: WAITING_FOR_RELEASE, attention: false },
    { key: 'needs-answer', title: 'Needs my answer', hint: 'A developer asked about a bug you reported', filters: { reporterId: me, status: 'NEEDS_INFO' }, where: { reporterId: me, status: BugStatus.NEEDS_INFO }, attention: true },
    { key: 'reported', title: 'Reported by me, still open', hint: 'Not closed yet', filters: { reporterId: me, status: csv([...OPEN_WORK, BugStatus.NEEDS_INFO, BugStatus.FIXED]) }, where: { reporterId: me, status: { not: BugStatus.CLOSED } }, attention: false },
  ];
  const admin: WorkGroup[] = [
    { key: 'unassigned', title: 'Unassigned', hint: 'Open bugs nobody has taken', filters: { assigneeId: 'none', status: csv(OPEN_WORK) }, where: { assigneeId: null, status: { in: OPEN_WORK } }, attention: true },
    { key: 'to-verify', title: 'Waiting for QA', hint: 'Fixed, or a reason suggested', filters: { status: 'FIXED' }, where: { status: BugStatus.FIXED }, attention: false },
    { key: 'reopened', title: 'Reopened', hint: 'Fixes that did not hold', filters: { status: 'REOPENED' }, where: { status: BugStatus.REOPENED }, attention: false },
    { key: 'needs-info', title: 'Waiting for information', hint: 'A developer is waiting on an answer', filters: { status: 'NEEDS_INFO' }, where: { status: BugStatus.NEEDS_INFO }, attention: false },
    { key: 'untriaged', title: 'Not triaged', hint: 'Open, with no priority set', filters: { priority: 'NONE', status: csv(OPEN_WORK) }, where: { priority: null, status: { in: OPEN_WORK } }, attention: false },
  ];
  return actor.role === Role.DEVELOPER ? dev : actor.role === Role.QA ? qa : admin;
}

/** The number beside "My work": how many bugs wait on this person. */
export async function attentionCount(actor: BugActor): Promise<number> {
  const groups = groupsFor(actor).filter((g) => g.attention);
  const counts = await Promise.all(groups.map((g) => db.bug.count({ where: g.where })));
  return counts.reduce((a, b) => a + b, 0);
}

export async function myWork(actor: BugActor) {
  const groups = groupsFor(actor);
  const filled = await Promise.all(
    groups.map(async (g) => {
      const [count, rows] = await Promise.all([
        db.bug.count({ where: g.where }),
        db.bug.findMany({
          where: g.where,
          orderBy: [{ severity: 'asc' }, { lastActivityAt: 'desc' }],
          take: 5,
          select: { number: true, title: true, status: true, severity: true, priority: true, resolution: true, lastActivityAt: true, module: { select: { name: true } } },
        }),
      ]);
      return {
        key: g.key,
        title: g.title,
        hint: g.hint,
        filters: g.filters,
        attention: g.attention,
        count,
        items: rows.map((r) => ({ number: r.number, key: bugKey(r.number), title: r.title, status: r.status, severity: r.severity, priority: r.priority, resolution: r.resolution, module: r.module.name, lastActivityAt: r.lastActivityAt })),
      };
    }),
  );
  return { groups: filled, attention: filled.filter((g) => g.attention).reduce((n, g) => n + g.count, 0) };
}

// ── The board (BT5) ─────────────────────────────────────────────────────────

/** The board's columns, in the order work flows. */
export const BOARD_COLUMNS: BugStatus[] = [BugStatus.OPEN, BugStatus.REOPENED, BugStatus.IN_PROGRESS, BugStatus.NEEDS_INFO, BugStatus.FIXED, BugStatus.CLOSED];
const BOARD_CARDS = 40;
/** The Closed column shows what was closed lately, not everything ever. */
const CLOSED_DAYS = 14;

/**
 * Every bug as a card under its status, most severe first, narrowed by the
 * list's filters. Each card says which moves this person may make, so the
 * page only offers a drop where the move is allowed; the move itself goes
 * through `moveBug`, with the same rules as anywhere else.
 */
export async function board(f: ListBugsInput, actor: BugActor, now = new Date()) {
  const base = whereOf({ ...f, status: [] });
  const columns = await Promise.all(
    BOARD_COLUMNS.map(async (status) => {
      const closed = status === BugStatus.CLOSED;
      const where: Prisma.BugWhereInput = { AND: [base, { status }, ...(closed ? [{ closedAt: { gte: new Date(now.getTime() - CLOSED_DAYS * 86_400_000) } }] : [])] };
      const [total, rows] = await Promise.all([
        db.bug.count({ where }),
        db.bug.findMany({ where, include: withModule, orderBy: closed ? [{ closedAt: 'desc' }] : [{ severity: 'asc' }, { lastActivityAt: 'desc' }], take: BOARD_CARDS }),
      ]);
      return { status, total, rows };
    }),
  );
  const who = await people(columns.flatMap((c) => c.rows.flatMap((r) => [r.reporterId, r.assigneeId])));
  return {
    closedDays: CLOSED_DAYS,
    columns: columns.map((c) => ({
      status: c.status,
      total: c.total,
      cards: c.rows.map((r) => ({ ...summary(r, who), actions: allowedActions(actor, r) })),
    })),
  };
}
