import { BugLinkKind, BugStatus, Prisma, Role, type Bug, type BugAttachment, type BugComment } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { TRACKER_ROLES, type BugActor } from './bug-access';
import { claimable, presentFile, removeFile } from './bug-files.service';
import { notify, peopleOn } from './bug-notify.service';
import { usableRelease } from './bug-releases.service';
import { linkReportedBug, reportableResult, testsOf } from './bug-testing.service';
import { GITHUB_ACTOR } from './bug-access';
import { allowedActions, BUG_LIMITS, bugKey, bugNumberFrom, titleWords, type CreateBugInput, type ListBugsInput, type UpdateBugInput } from './bug-rules';

/**
 * Bugs: report, find, read, edit, comment (docs/bug-tracker-plan.md, BT2).
 *
 * Platform-level data, reached only through requireBugAccess. Every change
 * leaves a BugEvent, so a bug's page can show who did what and when. The
 * fix-and-verify moves (status, assignment) are BT3; a new bug is OPEN and
 * goes to its module's default developer, if it has one.
 */

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

// ── Who may do what ─────────────────────────────────────────────────────────

/** The super admin and developers edit any bug; QA their own, or anyone's until it is closed. */
export function canEdit(actor: BugActor, bug: Pick<Bug, 'reporterId' | 'status'>): boolean {
  if (actor.role === Role.SUPER_ADMIN || actor.role === Role.DEVELOPER) return true;
  return bug.reporterId === actor.id || bug.status !== BugStatus.CLOSED;
}

// ── Reading ─────────────────────────────────────────────────────────────────

export async function people(ids: (string | null | undefined)[]): Promise<Map<string, { id: string; name: string; role: Role }>> {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  if (!unique.length) return new Map();
  const rows = await db.user.findMany({ where: { id: { in: unique } }, select: { id: true, name: true, role: true } });
  return new Map(rows.map((r) => [r.id, r]));
}
// A move GitHub made with nobody on the team to name (BT6) reads as GitHub's.
const person = (who: Map<string, { id: string; name: string; role: Role }>, id: string | null) => (id ? (who.get(id) ?? { id, name: id === GITHUB_ACTOR.id ? GITHUB_ACTOR.name : 'Unknown', role: null }) : null);

type ReleaseRef = { id: string; name: string; deployedAt: Date | null } | null;
type BugWithModule = Bug & { module: { id: string; name: string; archivedAt: Date | null }; fixedInRelease: ReleaseRef; foundInRelease: ReleaseRef };
const releaseRef = { select: { id: true, name: true, deployedAt: true } } as const;
export const withModule = { module: { select: { id: true, name: true, archivedAt: true } }, fixedInRelease: releaseRef, foundInRelease: releaseRef } satisfies Prisma.BugInclude;
const presentRelease = (r: ReleaseRef) => (r ? { id: r.id, name: r.name, deployed: !!r.deployedAt, deployedAt: r.deployedAt } : null);

/**
 * BT5: a bug waiting for QA whose fix is in a release that has not gone out
 * cannot be tested yet. With no release named, it is taken as testable.
 */
export const READY_TO_VERIFY: Prisma.BugWhereInput = { status: BugStatus.FIXED, OR: [{ fixedInReleaseId: null }, { fixedInRelease: { deployedAt: { not: null } } }] };
export const WAITING_FOR_RELEASE: Prisma.BugWhereInput = { status: BugStatus.FIXED, fixedInRelease: { deployedAt: null } };

export function summary(b: BugWithModule, who: Map<string, { id: string; name: string; role: Role }>, counts?: { comments: number; files: number }) {
  return {
    id: b.id,
    number: b.number,
    key: bugKey(b.number),
    type: b.type,
    title: b.title,
    app: b.app,
    module: { id: b.module.id, name: b.module.name, archived: !!b.module.archivedAt },
    environment: b.environment,
    tenantKind: b.tenantKind,
    affectedRole: b.affectedRole,
    severity: b.severity,
    priority: b.priority,
    status: b.status,
    resolution: b.resolution,
    /** The release the fix is in, and whether it has gone out. */
    fixedInRelease: presentRelease(b.fixedInRelease),
    reporter: person(who, b.reporterId),
    assignee: person(who, b.assigneeId),
    createdAt: b.createdAt,
    lastActivityAt: b.lastActivityAt,
    ...(counts ? { commentCount: counts.comments, fileCount: counts.files } : {}),
  };
}

export async function loadByNumber(number: number): Promise<BugWithModule> {
  const b = await db.bug.findUnique({ where: { number }, include: withModule });
  if (!b) throw new NotFoundError(`${bugKey(number)} was not found.`);
  return b;
}

async function presentComment(c: BugComment & { attachments: BugAttachment[] }, who: Map<string, { id: string; name: string; role: Role }>) {
  return {
    id: c.id,
    author: person(who, c.authorId),
    body: c.deletedAt ? '' : c.body,
    mentions: c.deletedAt ? [] : c.mentions.map((id) => person(who, id)).filter(Boolean),
    files: c.deletedAt ? [] : await Promise.all(c.attachments.map(presentFile)),
    createdAt: c.createdAt,
    editedAt: c.editedAt,
    deleted: !!c.deletedAt,
  };
}

/** One bug, with everything its page shows. */
export async function getBug(number: number, actor: BugActor) {
  const b = await loadByNumber(number);
  const [files, comments, events, watchers, linksFrom, linksTo, code, tests] = await Promise.all([
    db.bugAttachment.findMany({ where: { bugId: b.id }, orderBy: { createdAt: 'asc' } }),
    db.bugComment.findMany({ where: { bugId: b.id }, orderBy: { createdAt: 'asc' }, include: { attachments: { orderBy: { createdAt: 'asc' } } }, take: 500 }),
    db.bugEvent.findMany({ where: { bugId: b.id }, orderBy: { createdAt: 'asc' }, take: 500 }),
    db.bugWatcher.findMany({ where: { bugId: b.id }, select: { userId: true } }),
    db.bugLink.findMany({ where: { fromId: b.id }, include: { to: { select: { number: true, title: true, status: true } } } }),
    db.bugLink.findMany({ where: { toId: b.id }, include: { from: { select: { number: true, title: true, status: true } } } }),
    db.bugCodeLink.findMany({ where: { bugId: b.id }, orderBy: { createdAt: 'asc' }, take: 100 }),
    testsOf(b.id),
  ]);
  const who = await people([b.reporterId, b.assigneeId, ...comments.flatMap((c) => [c.authorId, ...c.mentions]), ...events.map((e) => e.actorId), ...watchers.map((w) => w.userId)]);
  const other = (x: { number: number; title: string; status: BugStatus }) => ({ number: x.number, key: bugKey(x.number), title: x.title, status: x.status });
  return {
    ...summary(b, who),
    steps: b.steps,
    expected: b.expected,
    actual: b.actual,
    appVersion: b.appVersion,
    foundInRelease: presentRelease(b.foundInRelease),
    device: b.device,
    pageUrl: b.pageUrl,
    videoUrl: b.videoUrl,
    fixNote: b.fixNote,
    fixLink: b.fixLink,
    fixedIn: b.fixedIn,
    reopenCount: b.reopenCount,
    closedAt: b.closedAt,
    updatedAt: b.updatedAt,
    files: await Promise.all(files.map(presentFile)),
    comments: await Promise.all(comments.map((c) => presentComment(c, who))),
    events: events.map((e) => ({ id: e.id, type: e.type, actor: person(who, e.actorId), changes: e.changes, createdAt: e.createdAt })),
    watchers: watchers.map((w) => person(who, w.userId)).filter(Boolean),
    watching: watchers.some((w) => w.userId === actor.id),
    links: [
      // "Related" reads the same from both ends; a duplicate points one way.
      ...linksFrom.map((l) => ({ id: l.id, kind: l.kind, direction: 'out' as const, bug: other(l.to) })),
      ...linksTo.map((l) => ({ id: l.id, kind: l.kind, direction: 'in' as const, bug: other(l.from) })),
    ],
    /** BT6: commits and pull requests on GitHub that name this bug. */
    code: code.map((c) => ({ id: c.id, kind: c.kind, repo: c.repo, ref: c.kind === 'COMMIT' ? c.ref.slice(0, 7) : `#${c.ref}`, url: c.url, title: c.title, author: c.author, branch: c.branch, fixes: c.fixes, state: c.state, createdAt: c.createdAt })),
    /** BT6: the test run items this bug is the failure of. */
    foundByTests: tests,
    can: { edit: canEdit(actor, b), actions: allowedActions(actor, b), assign: b.status !== BugStatus.CLOSED },
  };
}
export type PresentedBug = Awaited<ReturnType<typeof getBug>>;

export function whereOf(f: Omit<ListBugsInput, 'page' | 'limit' | 'sort'>): Prisma.BugWhereInput {
  const and: Prisma.BugWhereInput[] = [];
  if (f.q) {
    const n = bugNumberFrom(f.q);
    and.push({
      OR: [
        ...(n !== null ? [{ number: n }] : []),
        { title: { contains: f.q, mode: 'insensitive' } },
        { steps: { contains: f.q, mode: 'insensitive' } },
        { actual: { contains: f.q, mode: 'insensitive' } },
        { expected: { contains: f.q, mode: 'insensitive' } },
      ],
    });
  }
  if (f.status.length) and.push({ status: { in: f.status } });
  if (f.severity.length) and.push({ severity: { in: f.severity } });
  if (f.priority.length) {
    const set = f.priority.filter((p) => p !== 'NONE') as Exclude<(typeof f.priority)[number], 'NONE'>[];
    and.push({ OR: [...(set.length ? [{ priority: { in: set } }] : []), ...(f.priority.includes('NONE') ? [{ priority: null }] : [])] });
  }
  if (f.app.length) and.push({ app: { in: f.app } });
  if (f.environment.length) and.push({ environment: { in: f.environment } });
  if (f.type.length) and.push({ type: { in: f.type } });
  if (f.tenantKind.length) and.push({ tenantKind: { in: f.tenantKind } });
  if (f.moduleId) and.push({ moduleId: f.moduleId });
  if (f.assigneeId) and.push({ assigneeId: f.assigneeId === 'none' ? null : f.assigneeId });
  if (f.reporterId) and.push({ reporterId: f.reporterId });
  if (f.fixedInReleaseId) and.push({ fixedInReleaseId: f.fixedInReleaseId });
  if (f.foundInReleaseId) and.push({ foundInReleaseId: f.foundInReleaseId });
  if (f.deploy) and.push(f.deploy === 'ready' ? READY_TO_VERIFY : WAITING_FOR_RELEASE);
  if (f.olderThan) and.push({ createdAt: { lt: new Date(Date.now() - f.olderThan * 86_400_000) } });
  return and.length ? { AND: and } : {};
}

/**
 * Severity and priority sort by what they mean, not by their spelling;
 * Postgres orders an enum by the order its values were declared in.
 */
export function orderOf(sort: ListBugsInput['sort']): Prisma.BugOrderByWithRelationInput[] {
  return sort === 'newest'
    ? [{ createdAt: 'desc' }]
    : sort === 'oldest'
      ? [{ createdAt: 'asc' }]
      : sort === 'severity'
        ? [{ severity: 'asc' }, { lastActivityAt: 'desc' }]
        : sort === 'priority'
          ? [{ priority: { sort: 'asc', nulls: 'last' } }, { severity: 'asc' }, { lastActivityAt: 'desc' }]
          : [{ lastActivityAt: 'desc' }];
}

export async function listBugs(f: ListBugsInput) {
  const where = whereOf(f);
  const orderBy = orderOf(f.sort);
  const [rows, total, byStatus] = await Promise.all([
    db.bug.findMany({ where, include: { ...withModule, _count: { select: { comments: { where: { deletedAt: null } }, attachments: true } } }, orderBy, skip: (f.page - 1) * f.limit, take: f.limit }),
    db.bug.count({ where }),
    db.bug.groupBy({ by: ['status'], _count: { _all: true } }),
  ]);
  const who = await people(rows.flatMap((r) => [r.reporterId, r.assigneeId]));
  return {
    items: rows.map((r) => summary(r, who, { comments: r._count.comments, files: r._count.attachments })),
    total,
    page: f.page,
    limit: f.limit,
    hasMore: (f.page - 1) * f.limit + rows.length < total,
    /** Every bug by status, whatever the filters: the tabs' numbers. */
    counts: Object.fromEntries(byStatus.map((c) => [c.status, c._count._all])) as Partial<Record<BugStatus, number>>,
  };
}

/** Open bugs whose titles share words with this one: shown while a report is typed. */
export async function similarBugs(title: string, exceptNumber?: number) {
  const words = titleWords(title);
  if (!words.length) return { items: [] };
  const rows = await db.bug.findMany({
    where: {
      status: { not: BugStatus.CLOSED },
      ...(exceptNumber ? { number: { not: exceptNumber } } : {}),
      OR: words.map((w) => ({ title: { contains: w, mode: 'insensitive' as const } })),
    },
    select: { number: true, title: true, status: true, severity: true, lastActivityAt: true },
    orderBy: { lastActivityAt: 'desc' },
    take: 60,
  });
  const scored = rows
    .map((r) => ({ r, hits: words.filter((w) => r.title.toLowerCase().includes(w)).length }))
    // One shared word is noise unless the title only has one word worth matching.
    .filter((x) => x.hits >= Math.min(2, words.length))
    .sort((a, b) => b.hits - a.hits || b.r.lastActivityAt.getTime() - a.r.lastActivityAt.getTime())
    .slice(0, 5);
  return { items: scored.map(({ r }) => ({ number: r.number, key: bugKey(r.number), title: r.title, status: r.status, severity: r.severity })) };
}

// ── Writing ─────────────────────────────────────────────────────────────────

async function assertModule(moduleId: string, allowArchived: boolean) {
  const m = await db.bugModule.findUnique({ where: { id: moduleId } });
  if (!m) throw new BadRequestError('Choose a module from the list.', 'MODULE_NOT_FOUND');
  if (m.archivedAt && !allowArchived) throw new BadRequestError('That module is archived. Choose another.', 'MODULE_ARCHIVED');
  return m;
}

const touch = (bugId: string, at = new Date()) => db.bug.update({ where: { id: bugId }, data: { lastActivityAt: at } });
const watch = (bugId: string, userIds: string[]) =>
  userIds.length ? db.bugWatcher.createMany({ data: [...new Set(userIds)].map((userId) => ({ bugId, userId })), skipDuplicates: true }) : Promise.resolve();

export async function createBug(input: CreateBugInput, actor: BugActor) {
  const { attachmentIds, testResultId, ...fields } = input;
  // Reported from a test run: the new bug becomes that item's failure.
  const test = testResultId ? await reportableResult(testResultId) : null;
  const module = await assertModule(fields.moduleId, false);
  // A release from the list names the version: the two never disagree.
  if (fields.foundInReleaseId) fields.appVersion = (await usableRelease(fields.foundInReleaseId, fields.app, 'found')).name;
  const files = await claimable(attachmentIds, actor);
  // The module's developer gets it, while their account is on.
  const assignee = module.defaultDeveloperId
    ? await db.user.findFirst({ where: { id: module.defaultDeveloperId, role: Role.DEVELOPER, deactivatedAt: null }, select: { id: true } })
    : null;

  const bug = await db.$transaction(async (tx) => {
    const created = await tx.bug.create({
      data: {
        ...fields,
        expected: fields.expected ?? null,
        actual: fields.actual ?? null,
        appVersion: fields.appVersion ?? null,
        foundInReleaseId: fields.foundInReleaseId ?? null,
        device: fields.device ?? null,
        pageUrl: fields.pageUrl ?? null,
        videoUrl: fields.videoUrl ?? null,
        priority: fields.priority ?? null,
        reporterId: actor.id,
        assigneeId: assignee?.id ?? null,
      },
    });
    if (files.length) await tx.bugAttachment.updateMany({ where: { id: { in: files.map((f) => f.id) } }, data: { bugId: created.id } });
    const how = { ...(assignee ? { assignee: { from: null, to: assignee.id }, via: 'module' } : {}), ...(test ? { test: { run: test.run, item: test.item } } : {}) };
    await tx.bugEvent.create({ data: { bugId: created.id, actorId: actor.id, type: 'CREATED', changes: Object.keys(how).length ? how : Prisma.JsonNull } });
    if (test) await linkReportedBug(tx, test.id, created.id, actor);
    await tx.bugWatcher.createMany({ data: [...new Set([actor.id, ...(assignee ? [assignee.id] : [])])].map((userId) => ({ bugId: created.id, userId })) });
    return created;
  });
  if (assignee) await notify({ bugId: bug.id, actor, to: [{ userId: assignee.id, kind: 'NEW_ASSIGNED' }] });
  return getBug(bug.number, actor);
}

/** Long text is recorded as "changed", not copied into the history. */
const LONG = new Set(['steps', 'expected', 'actual']);
/** Recorded through the field it fills (the version's name), not as an id. */
const SILENT = new Set(['foundInReleaseId']);

export async function updateBug(number: number, input: UpdateBugInput, actor: BugActor) {
  const bug = await loadByNumber(number);
  if (!canEdit(actor, bug)) throw new ForbiddenError('This bug is closed, so only its reporter, a developer or the super admin can edit it.');
  // Keeping an archived module is fine; moving a bug into one is not.
  if (input.moduleId !== undefined && input.moduleId !== bug.moduleId) await assertModule(input.moduleId, false);

  const merged = { ...bug, ...input };
  input = { ...input };
  if (input.foundInReleaseId) {
    input.appVersion = (await usableRelease(input.foundInReleaseId, merged.app, 'found')).name;
  } else if (input.foundInReleaseId === undefined && bug.foundInReleaseId) {
    // A version typed by hand replaces the release; so does moving the bug to another app.
    if ((input.appVersion !== undefined && input.appVersion !== bug.appVersion) || (input.app !== undefined && input.app !== bug.app)) input.foundInReleaseId = null;
  }
  if (merged.type === 'BUG') {
    for (const [key, label] of [['expected', 'Expected result'], ['actual', 'Actual result']] as const) {
      if ((merged[key] ?? '').length < BUG_LIMITS.result.min) throw new BadRequestError(`${label} must be at least ${BUG_LIMITS.result.min} characters`, 'RESULT_REQUIRED');
    }
  }

  const changes: Record<string, unknown> = {};
  let silent = false;
  for (const [k, v] of Object.entries(input)) {
    const before = (bug as Record<string, unknown>)[k] ?? null;
    if (v === undefined || (v ?? null) === before) continue;
    if (SILENT.has(k)) {
      silent = true;
      continue;
    }
    changes[k] = LONG.has(k) ? { changed: true } : { from: before, to: v ?? null };
  }
  if (!Object.keys(changes).length) {
    // Only the link to a release changed (the version text was already its name).
    if (silent) await db.bug.update({ where: { id: bug.id }, data: { foundInReleaseId: input.foundInReleaseId ?? null } });
    return getBug(number, actor);
  }

  await db.$transaction([
    db.bug.update({ where: { id: bug.id }, data: { ...input, lastActivityAt: new Date() } }),
    db.bugEvent.create({ data: { bugId: bug.id, actorId: actor.id, type: 'EDITED', changes: changes as Prisma.InputJsonObject } }),
  ]);
  return getBug(number, actor);
}

/** More files on an existing bug: anyone on the tracker, up to ten in all. */
export async function addFiles(number: number, attachmentIds: string[], actor: BugActor) {
  const bug = await loadByNumber(number);
  const files = await claimable(attachmentIds, actor);
  if (!files.length) throw new BadRequestError('Choose a file to attach.', 'NO_FILE');
  const have = await db.bugAttachment.count({ where: { bugId: bug.id } });
  if (have + files.length > BUG_LIMITS.filesPerItem) throw new BadRequestError(`A bug can have at most ${BUG_LIMITS.filesPerItem} files. Put more on a comment.`, 'TOO_MANY_FILES');
  await db.$transaction([
    db.bugAttachment.updateMany({ where: { id: { in: files.map((f) => f.id) } }, data: { bugId: bug.id } }),
    db.bugEvent.create({ data: { bugId: bug.id, actorId: actor.id, type: 'FILE_ADDED', changes: { files: files.map((f) => f.filename) } } }),
    touch(bug.id),
  ]);
  return getBug(number, actor);
}

/** Remove a file (its uploader or the super admin); a bug's history keeps its name. */
export async function deleteFile(id: string, actor: BugActor) {
  const a = await removeFile(id, actor);
  const bugId = a.bugId ?? (a.commentId ? (await db.bugComment.findUnique({ where: { id: a.commentId }, select: { bugId: true } }))?.bugId : null);
  if (bugId) {
    await db.$transaction([db.bugEvent.create({ data: { bugId, actorId: actor.id, type: 'FILE_REMOVED', changes: { files: [a.filename] } } }), touch(bugId)]);
  }
  return { ok: true };
}

// ── Comments ────────────────────────────────────────────────────────────────

/** The mentioned ids that are real, switched-on members. */
async function validMentions(ids: string[]): Promise<string[]> {
  if (!ids.length) return [];
  const rows = await db.user.findMany({ where: { id: { in: ids }, role: { in: MEMBER_ROLES }, deactivatedAt: null }, select: { id: true } });
  return rows.map((r) => r.id);
}

export async function addComment(number: number, input: { body: string; mentionIds: string[]; attachmentIds: string[] }, actor: BugActor) {
  const bug = await loadByNumber(number);
  const [files, mentions] = await Promise.all([claimable(input.attachmentIds, actor), validMentions(input.mentionIds)]);
  // Who was on the bug before this comment: they hear of it. Someone it calls in hears they were mentioned.
  const onIt = await peopleOn(bug.id, bug.assigneeId);
  await db.$transaction(async (tx) => {
    const c = await tx.bugComment.create({ data: { bugId: bug.id, authorId: actor.id, body: input.body, mentions } });
    if (files.length) await tx.bugAttachment.updateMany({ where: { id: { in: files.map((f) => f.id) } }, data: { commentId: c.id } });
    await tx.bug.update({ where: { id: bug.id }, data: { lastActivityAt: new Date() } });
    // Whoever joins the conversation, or is called into it, follows the bug.
    await tx.bugWatcher.createMany({ data: [...new Set([actor.id, ...mentions])].map((userId) => ({ bugId: bug.id, userId })), skipDuplicates: true });
  });
  await notify({
    bugId: bug.id,
    actor,
    to: [...mentions.map((userId) => ({ userId, kind: 'MENTION' as const })), ...onIt.map((userId) => ({ userId, kind: 'COMMENT' as const }))],
    snippet: input.body,
  });
  return getBug(number, actor);
}

async function loadComment(id: string) {
  const c = await db.bugComment.findUnique({ where: { id }, include: { bug: { select: { number: true } } } });
  if (!c || c.deletedAt) throw new NotFoundError('Comment not found.');
  return c;
}

export async function editComment(id: string, input: { body: string; mentionIds: string[] }, actor: BugActor) {
  const c = await loadComment(id);
  if (c.authorId !== actor.id) throw new ForbiddenError('Only its author can edit a comment.');
  const mentions = await validMentions(input.mentionIds);
  await db.bugComment.update({ where: { id }, data: { body: input.body, mentions, editedAt: new Date() } });
  await watch(c.bugId, mentions);
  // Only the people the edit newly calls in: the others were told when it was written.
  const added = mentions.filter((m) => !c.mentions.includes(m));
  if (added.length) await notify({ bugId: c.bugId, actor, to: added.map((userId) => ({ userId, kind: 'MENTION' as const })), snippet: input.body });
  return getBug(c.bug.number, actor);
}

/** Remove a comment: its author or the super admin. Its place in the thread stays, empty. */
export async function deleteComment(id: string, actor: BugActor) {
  const c = await loadComment(id);
  if (c.authorId !== actor.id && actor.role !== Role.SUPER_ADMIN) throw new ForbiddenError('Only its author, or the super admin, can remove a comment.');
  const files = await db.bugAttachment.findMany({ where: { commentId: id } });
  // The comment's own files go with it (they are its author's, so the same person, or the super admin, may remove them).
  for (const f of files) await removeFile(f.id, actor);
  await db.bugComment.update({ where: { id }, data: { body: '', mentions: [], deletedAt: new Date() } });
  return getBug(c.bug.number, actor);
}

// ── Watching and links ──────────────────────────────────────────────────────

export async function setWatching(number: number, watching: boolean, actor: BugActor) {
  const bug = await loadByNumber(number);
  if (watching) await watch(bug.id, [actor.id]);
  else await db.bugWatcher.deleteMany({ where: { bugId: bug.id, userId: actor.id } });
  return getBug(number, actor);
}

export async function linkRelated(number: number, toNumber: number, actor: BugActor) {
  if (number === toNumber) throw new BadRequestError('A bug cannot be related to itself.', 'SAME_BUG');
  const [from, to] = await Promise.all([loadByNumber(number), loadByNumber(toNumber)]);
  const exists = await db.bugLink.findFirst({ where: { kind: BugLinkKind.RELATED, OR: [{ fromId: from.id, toId: to.id }, { fromId: to.id, toId: from.id }] } });
  if (exists) throw new ConflictError(`${bugKey(toNumber)} is already linked to this bug.`, 'ALREADY_LINKED');
  await db.$transaction([
    db.bugLink.create({ data: { fromId: from.id, toId: to.id, kind: BugLinkKind.RELATED, createdById: actor.id } }),
    db.bugEvent.create({ data: { bugId: from.id, actorId: actor.id, type: 'LINKED', changes: { bug: bugKey(toNumber) } } }),
    db.bugEvent.create({ data: { bugId: to.id, actorId: actor.id, type: 'LINKED', changes: { bug: bugKey(number) } } }),
    touch(from.id),
  ]);
  return getBug(number, actor);
}

export async function unlink(number: number, linkId: string, actor: BugActor) {
  const bug = await loadByNumber(number);
  const link = await db.bugLink.findFirst({ where: { id: linkId, kind: BugLinkKind.RELATED, OR: [{ fromId: bug.id }, { toId: bug.id }] }, include: { from: { select: { id: true, number: true } }, to: { select: { id: true, number: true } } } });
  if (!link) throw new NotFoundError('That link was not found.');
  await db.$transaction([
    db.bugLink.delete({ where: { id: link.id } }),
    db.bugEvent.create({ data: { bugId: link.from.id, actorId: actor.id, type: 'UNLINKED', changes: { bug: bugKey(link.to.number) } } }),
    db.bugEvent.create({ data: { bugId: link.to.id, actorId: actor.id, type: 'UNLINKED', changes: { bug: bugKey(link.from.number) } } }),
  ]);
  return getBug(number, actor);
}
