/**
 * Bug tracker (docs/bug-tracker-plan.md): BT1 the team and the modules; BT2
 * files, bugs, comments and history; BT3 the fix-and-verify loop, assignment,
 * bulk changes and My work; BT4 notifications and their emails, the dashboard,
 * the Excel export and the Monday summary; BT5 releases and the board; BT6 test
 * checklists and runs, and GitHub's commit and pull request links. S3 is stood
 * in for, and so is the mail sender; GitHub's deliveries are handed to the
 * handler directly (the signature check is the permission audit's, over HTTP).
 *
 * Runs against its own THROWAWAY schema (hc_bug_test), set up and dropped by
 * `npm run test:isolation`. Email goes to the log, never out.
 */
import test from 'node:test';
import assert from 'node:assert/strict';
import { PrismaClient, Role } from '@prisma/client';
import { BadRequestError, ConflictError, NotFoundError } from '../lib/errors';
import { alwaysTwoStep } from '../lib/permissions';
import * as team from '../modules/bug-tracker/bug-team.service';
import * as modules from '../modules/bug-tracker/bug-modules.service';
import * as bugs from '../modules/bug-tracker/bug-bugs.service';
import * as files from '../modules/bug-tracker/bug-files.service';
import * as workflow from '../modules/bug-tracker/bug-workflow.service';
import * as notes from '../modules/bug-tracker/bug-notify.service';
import * as insights from '../modules/bug-tracker/bug-insights.service';
import { bugTick } from '../modules/bug-tracker/bug-jobs';
import * as releases from '../modules/bug-tracker/bug-releases.service';
import * as testing from '../modules/bug-tracker/bug-testing.service';
import * as checklistIo from '../modules/bug-tracker/bug-checklist-io.service';
import * as github from '../modules/bug-tracker/bug-github.service';
import { env } from '../config/env';
import { allowedActions, bugNumberFrom, bulkSchema, commentSchema, createBugSchema, editCommentSchema, listBugsSchema, moveSchema, updateBugSchema } from '../modules/bug-tracker/bug-rules';
import type { BugActor } from '../modules/bug-tracker/bug-access';

const raw = new PrismaClient();

/** Every email the tracker would have sent, instead of sending it. */
const sent: { to: string; subject: string; text: string }[] = [];
notes.mail.send = async (to, subject, text) => {
  sent.push({ to, subject, text });
  return { sent: false, mode: 'log' };
};
let admin: BugActor = { id: '', name: 'Platform Owner', role: Role.SUPER_ADMIN };
let qaId = '';
let devId = '';
let hostelAdminId = '';

test('bugs: clean slate (throwaway schema)', async () => {
  await raw.bugModule.deleteMany({});
  await raw.user.deleteMany({ where: { email: { endsWith: '@bugs.test' } } });
  await raw.tenant.deleteMany({ where: { name: 'Bug Test Hostel' } });
  const sa = await raw.user.create({ data: { role: Role.SUPER_ADMIN, tenantId: null, name: 'Platform Owner', email: 'owner@bugs.test', passwordHash: 'x' } });
  admin = { id: sa.id, name: sa.name, role: sa.role };
  const tenant = await raw.tenant.create({ data: { name: 'Bug Test Hostel' } });
  hostelAdminId = (await raw.user.create({ data: { role: Role.HOSTEL_ADMIN, tenantId: tenant.id, name: 'Hostel Admin', email: 'ha@bugs.test', passwordHash: 'x' } })).id;
});

test('bugs team: QA and developers are invited with no tenant, a locked second step and a link', async () => {
  const qa = await team.createMember({ name: 'Meera QA', email: 'meera@bugs.test', role: Role.QA }, admin);
  assert.equal(qa.member.role, Role.QA);
  assert.equal(qa.member.status, 'INVITED');
  assert.equal(qa.delivery.kind, 'INVITE');
  assert.equal(qa.member.pendingLink?.kind, 'INVITE');
  const dev = await team.createMember({ name: 'Ravi Dev', email: 'ravi@bugs.test', role: Role.DEVELOPER, phone: '9876500000' }, admin);
  assert.equal(dev.member.role, Role.DEVELOPER);
  qaId = qa.member.id;
  devId = dev.member.id;

  const row = await raw.user.findUniqueOrThrow({ where: { id: qaId } });
  assert.equal(row.tenantId, null, 'a tester belongs to no hostel');
  assert.equal(row.twoFactorEnabled, true);
  assert.ok(alwaysTwoStep(Role.QA) && alwaysTwoStep(Role.DEVELOPER), 'both always get a sign-in code');
  await assert.rejects(() => team.createMember({ name: 'Again', email: 'meera@bugs.test', role: Role.DEVELOPER }, admin), ConflictError);
  await assert.rejects(() => team.createMember({ name: 'Taken', email: 'ha@bugs.test', role: Role.QA }, admin), /already registered/);
});

test('bugs team: the endpoints only ever reach tracker accounts', async () => {
  const all = await team.listMembers({});
  assert.deepEqual(all.members.map((m) => m.email).sort(), ['meera@bugs.test', 'ravi@bugs.test']);
  assert.deepEqual((await team.listMembers({ role: Role.DEVELOPER })).members.map((m) => m.name), ['Ravi Dev']);
  assert.deepEqual((await team.listMembers({ q: 'meer' })).members.map((m) => m.name), ['Meera QA']);
  // A hostel's admin and the super admin are not "team members" here.
  for (const id of [hostelAdminId, admin.id]) {
    await assert.rejects(() => team.updateMember(id, { name: 'Hacked' }), NotFoundError);
    await assert.rejects(() => team.deactivateMember(id), NotFoundError);
    await assert.rejects(() => team.sendPasswordLink(id, admin), NotFoundError);
    await assert.rejects(() => team.signOutEverywhere(id), NotFoundError);
  }
  assert.equal((await raw.user.findUniqueOrThrow({ where: { id: hostelAdminId } })).name, 'Hostel Admin');
  // Who a bug can go to: the team and the super admin, never a hostel account.
  const active = await team.activeMembers();
  assert.deepEqual(active.map((m) => m.role).sort(), [Role.DEVELOPER, Role.QA, Role.SUPER_ADMIN].sort());
});

test('bugs modules: a new tracker starts with HostelCare’s modules, once', async () => {
  const first = await modules.listModules();
  assert.ok(first.length >= 15);
  assert.ok(first.some((m) => m.name === 'Billing and payments') && first.some((m) => m.name === 'Other'));
  assert.equal(first[0].sortOrder, 0);
  assert.equal((await modules.listModules()).length, first.length, 'not seeded twice');
  assert.deepEqual(modules.BUG_APPS.map((a) => a.key), ['WEB_APP', 'ANDROID_APP', 'IOS_APP', 'API', 'WEBSITE']);
});

let moduleId = '';

test('bugs modules: add, rename, default developer, archive and restore', async () => {
  const m = await modules.createModule({ name: 'Bed allocation' });
  moduleId = m.id;
  assert.equal(m.archived, false);
  assert.equal(m.defaultDeveloper, null);
  // One module per name, whatever the capitals.
  await assert.rejects(() => modules.createModule({ name: 'bed ALLOCATION' }), ConflictError);
  await assert.rejects(() => modules.updateModule(moduleId, { name: 'Mess' }), /already exists/);

  // Only a developer whose account is on can be a module's default.
  await assert.rejects(() => modules.updateModule(moduleId, { defaultDeveloperId: qaId }), BadRequestError);
  await assert.rejects(() => modules.updateModule(moduleId, { defaultDeveloperId: hostelAdminId }), /developer/);
  const withDev = await modules.updateModule(moduleId, { defaultDeveloperId: devId, name: 'Bed allocation and transfers' });
  assert.deepEqual(withDev.defaultDeveloper, { id: devId, name: 'Ravi Dev' });
  assert.equal(withDev.name, 'Bed allocation and transfers');

  const archived = await modules.updateModule(moduleId, { archived: true });
  assert.equal(archived.archived, true);
  assert.ok(!(await modules.listModules()).some((x) => x.id === moduleId), 'hidden from new reports');
  assert.ok((await modules.listModules({ includeArchived: true })).some((x) => x.id === moduleId), 'still there for the super admin');
  await assert.rejects(() => modules.createModule({ name: 'Bed allocation and transfers' }), /Restore it instead/);
  assert.equal((await modules.updateModule(moduleId, { archived: false })).archived, false);
});

test('bugs modules: the order is the super admin’s', async () => {
  const all = await modules.listModules({ includeArchived: true });
  const reversed = [...all].reverse().map((m) => m.id);
  const after = await modules.reorderModules(reversed);
  assert.deepEqual(after.map((m) => m.id), reversed);
  await assert.rejects(() => modules.reorderModules([reversed[0], reversed[0]]), BadRequestError);
  await assert.rejects(() => modules.reorderModules(['00000000-0000-0000-0000-000000000000']), BadRequestError);
});

test('bugs team: a changed role or email signs the person out; a module loses a developer who is no longer one', async () => {
  const before = await raw.user.findUniqueOrThrow({ where: { id: devId } });
  assert.equal(before.sessionsRevokedAt, null);
  const renamed = await team.updateMember(devId, { name: 'Ravi K' });
  assert.equal(renamed.name, 'Ravi K');
  assert.equal((await raw.user.findUniqueOrThrow({ where: { id: devId } })).sessionsRevokedAt, null, 'a new name ends no session');

  const moved = await team.updateMember(devId, { role: Role.QA });
  assert.equal(moved.role, Role.QA);
  assert.ok((await raw.user.findUniqueOrThrow({ where: { id: devId } })).sessionsRevokedAt, 'a new role ends every session');
  assert.equal((await modules.listModules({ includeArchived: true })).find((m) => m.id === moduleId)?.defaultDeveloper, null);

  await team.updateMember(devId, { role: Role.DEVELOPER });
  await modules.updateModule(moduleId, { defaultDeveloperId: devId });
  await assert.rejects(() => team.updateMember(qaId, { email: 'ravi@bugs.test' }), ConflictError);
  const mailed = await team.updateMember(qaId, { email: 'meera.new@bugs.test' });
  assert.equal(mailed.email, 'meera.new@bugs.test');
  assert.equal(mailed.pendingLink, null, 'a link sent to the old address stops working');
});

test('bugs team: switching off ends access at once and frees their modules; back on works', async () => {
  const off = await team.deactivateMember(devId);
  assert.equal(off.status, 'DEACTIVATED');
  const row = await raw.user.findUniqueOrThrow({ where: { id: devId } });
  assert.ok(row.deactivatedAt && row.sessionsRevokedAt);
  assert.equal((await modules.listModules({ includeArchived: true })).find((m) => m.id === moduleId)?.defaultDeveloper, null);
  assert.ok(!(await team.activeMembers()).some((m) => m.id === devId), 'not offered for new work');
  await assert.rejects(() => team.sendPasswordLink(devId, admin), /Switch the account back on/);
  await assert.rejects(() => modules.updateModule(moduleId, { defaultDeveloperId: devId }), BadRequestError);

  const on = await team.reactivateMember(devId);
  assert.notEqual(on.status, 'DEACTIVATED');
  const link = await team.sendPasswordLink(devId, admin);
  assert.equal(link.delivery.kind, 'INVITE', 'never signed in: still an invite, not a reset');
});

// ── BT2: files, bugs, comments, history ────────────────────────────────────

const stored = new Map<string, Buffer>();
files.storage.put = async (key, body) => void stored.set(key, body);
files.storage.presign = async (key, opts) => `https://s3.test/${key}?signed&${opts.inline ? 'inline' : 'attachment'}`;
files.storage.remove = async (key) => void stored.delete(key);

/** The smallest PNG header the size reader needs. */
function png(width = 1280, height = 720): Buffer {
  const b = Buffer.alloc(33);
  Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(b, 0);
  b.writeUInt32BE(13, 8);
  b.write('IHDR', 12, 'ascii');
  b.writeUInt32BE(width, 16);
  b.writeUInt32BE(height, 20);
  return b;
}

let qa: BugActor = { id: '', name: '', role: Role.QA };
let qa2: BugActor = { id: '', name: '', role: Role.QA };
let dev: BugActor = { id: '', name: '', role: Role.DEVELOPER };
let billingId = '';
const report = (over: Record<string, unknown> = {}) =>
  createBugSchema.parse({
    title: 'Invoice total is wrong after a partial payment',
    steps: '1. Open a resident with a ₹6,000 invoice\n2. Record ₹2,000\n3. Open the invoice',
    expected: 'Balance shows ₹4,000',
    actual: 'Balance shows ₹6,000',
    app: 'WEB_APP',
    moduleId: billingId,
    severity: 'MAJOR',
    ...over,
  });

test('bugs BT2: set up two testers, a developer and a module that sends its bugs to them', async () => {
  const a = await team.createMember({ name: 'Asha QA', email: 'asha@bugs.test', role: Role.QA }, admin);
  const b = await team.createMember({ name: 'Bina QA', email: 'bina@bugs.test', role: Role.QA }, admin);
  const d = await team.createMember({ name: 'Dev Kumar', email: 'devk@bugs.test', role: Role.DEVELOPER }, admin);
  qa = { id: a.member.id, name: 'Asha QA', role: Role.QA };
  qa2 = { id: b.member.id, name: 'Bina QA', role: Role.QA };
  dev = { id: d.member.id, name: 'Dev Kumar', role: Role.DEVELOPER };
  billingId = (await modules.listModules()).find((m) => m.name === 'Billing and payments')!.id;
  await modules.updateModule(billingId, { defaultDeveloperId: dev.id });
});

test('bugs files: the type comes from the bytes; only images, PDFs and text are taken, up to 10 MB', async () => {
  assert.equal(files.sniffFile(png(), 'x.exe')?.kind, 'IMAGE');
  assert.deepEqual(files.sniffFile(Buffer.from('GIF89a\x10\x00\x08\x00rest', 'latin1'), 'a.gif'), { kind: 'IMAGE', mime: 'image/gif', ext: 'gif', width: 16, height: 8 });
  assert.equal(files.sniffFile(Buffer.from('%PDF-1.7 …'), 'a.png')?.kind, 'PDF');
  assert.equal(files.sniffFile(Buffer.from('2026-11-16 ERROR something failed\n'), 'server.log')?.ext, 'log');
  // An HTML or script file is only ever stored and served as plain text.
  assert.equal(files.sniffFile(Buffer.from('<script>alert(1)</script>'), 'x.html')?.mime, 'text/plain; charset=utf-8');
  assert.equal(files.sniffFile(Buffer.from([0x4d, 0x5a, 0x00, 0x03, 0xff, 0xfe]), 'x.txt'), null, 'a binary is refused whatever its name');

  await assert.rejects(() => files.uploadFile({ body: Buffer.alloc(0), filename: 'a.png' }, qa), /Choose a file/);
  await assert.rejects(() => files.uploadFile({ body: Buffer.alloc(10 * 1024 * 1024 + 1, 0x61), filename: 'big.txt' }, qa), /at most 10 MB/);
  await assert.rejects(() => files.uploadFile({ body: Buffer.from([0x00, 0x01, 0x02, 0x03]), filename: 'video.mp4' }, qa), /add its link/);
  const f = await files.uploadFile({ body: png(), filename: 'screen shot/../1.png' }, qa);
  assert.ok(f.key.startsWith('platform/bug-tracker/'), 'outside every tenant prefix');
  assert.ok(!f.filename.includes('/'));
  assert.equal(f.width, 1280);
  assert.ok(stored.has(f.key));
  assert.match((await files.presentFile(f)).url ?? '', /inline/);
  await files.removeFile(f.id, qa);
});

let bug1 = 0;
let bug2 = 0;

test('bugs report: numbered in order, goes to the module’s developer, files attached, both follow it', async () => {
  const shot = await files.uploadFile({ body: png(), filename: 'invoice.png' }, qa);
  const log = await files.uploadFile({ body: Buffer.from('GET /api/invoices 500\n'), filename: 'network.log' }, qa);
  const b = await bugs.createBug(report({ attachmentIds: [shot.id, log.id], device: 'Chrome 131 on Windows 11', pageUrl: 'https://app.hostelcare.co.in/#invoices', tenantKind: 'PG', affectedRole: 'HOSTEL_ADMIN' }), qa);
  bug1 = b.number;
  assert.equal(b.key, `BUG-${b.number}`);
  assert.equal(b.status, 'OPEN');
  assert.equal(b.reporter?.name, 'Asha QA');
  assert.equal(b.assignee?.name, 'Dev Kumar', 'the module’s default developer');
  assert.deepEqual(b.files.map((f) => f.filename), ['invoice.png', 'network.log']);
  assert.match(b.files[1].url ?? '', /attachment/, 'a log downloads; it is not opened by the browser');
  assert.deepEqual(b.watchers.map((w) => w!.name).sort(), ['Asha QA', 'Dev Kumar']);
  assert.equal(b.watching, true);
  assert.equal(b.events[0].type, 'CREATED');
  assert.equal(b.priority, null, 'not triaged yet');

  const second = await bugs.createBug(report({ title: 'Mess menu shows last week', steps: '1. Open the mess tab on Monday morning', expected: 'This week’s menu', actual: 'Last week’s menu', moduleId: (await modules.listModules()).find((m) => m.name === 'Mess')!.id, severity: 'MINOR', app: 'ANDROID_APP' }), qa2);
  bug2 = second.number;
  assert.equal(second.number, b.number + 1);
  assert.equal(second.assignee, null, 'that module has no default developer');
});

test('bugs report: what is refused', async () => {
  // A bug needs its expected and actual results; a suggestion does not.
  assert.throws(() => report({ actual: '' }), /Actual result/);
  assert.throws(() => report({ title: 'abc' }), /at least 5/);
  assert.throws(() => report({ videoUrl: 'http://insecure.test/v.mp4' }), /https/);
  assert.throws(() => report({ status: 'CLOSED' }), /Unrecognized key/);
  assert.doesNotThrow(() => report({ type: 'SUGGESTION', expected: null, actual: null }));
  // Someone else's file, or one already on a bug, can't be claimed by naming its id.
  const mine = await files.uploadFile({ body: png(), filename: 'mine.png' }, qa);
  await assert.rejects(() => bugs.createBug(report({ attachmentIds: [mine.id] }), qa2), /could not be attached/);
  const onBug1 = (await bugs.getBug(bug1, qa)).files[0].id;
  await assert.rejects(() => bugs.createBug(report({ attachmentIds: [onBug1] }), qa), /could not be attached/);
  await files.removeFile(mine.id, qa);
  // An archived module takes no new bugs.
  const arch = await modules.createModule({ name: 'Retired module' });
  await modules.updateModule(arch.id, { archived: true });
  await assert.rejects(() => bugs.createBug(report({ moduleId: arch.id }), qa), /archived/);
  await assert.rejects(() => bugs.createBug(report({ moduleId: '00000000-0000-0000-0000-000000000000' }), qa), /Choose a module/);
});

test('bugs edit: who may, and the history records what changed', async () => {
  // Another tester edits an open bug; the change is recorded with before and after.
  const edited = await bugs.updateBug(bug1, updateBugSchema.parse({ severity: 'CRITICAL', priority: 'P1', steps: '1. New steps that are long enough' }), qa2);
  assert.equal(edited.severity, 'CRITICAL');
  const ev = edited.events[edited.events.length - 1];
  assert.equal(ev.type, 'EDITED');
  assert.equal(ev.actor?.name, 'Bina QA');
  assert.deepEqual((ev.changes as Record<string, unknown>).severity, { from: 'MAJOR', to: 'CRITICAL' });
  assert.deepEqual((ev.changes as Record<string, unknown>).steps, { changed: true }, 'long text is not copied into the history');
  // Saving the same values again records nothing.
  const same = await bugs.updateBug(bug1, updateBugSchema.parse({ severity: 'CRITICAL' }), qa2);
  assert.equal(same.events.length, edited.events.length);
  // A bug can't lose the results it needs.
  await assert.rejects(() => bugs.updateBug(bug1, updateBugSchema.parse({ actual: null }), qa), /Actual result/);

  // Closed: its reporter, a developer or the super admin; not another tester.
  await raw.bug.update({ where: { number: bug1 }, data: { status: 'CLOSED' } });
  assert.equal((await bugs.getBug(bug1, qa2)).can.edit, false);
  await assert.rejects(() => bugs.updateBug(bug1, updateBugSchema.parse({ title: 'Changed by another tester' }), qa2), /closed/);
  for (const who of [qa, dev, admin]) assert.equal((await bugs.updateBug(bug1, updateBugSchema.parse({ appVersion: `web-${who.role}` }), who)).appVersion, `web-${who.role}`);
  await raw.bug.update({ where: { number: bug1 }, data: { status: 'OPEN' } });
});

test('bugs list: search by key or text, filters, sorting and counts', async () => {
  const parse = (q: Record<string, unknown> = {}) => listBugsSchema.parse(q);
  const all = await bugs.listBugs(parse());
  assert.equal(all.total, 2);
  assert.equal(all.counts.OPEN, 2);
  assert.equal(all.items.find((i) => i.number === bug1)?.fileCount, 2);
  assert.deepEqual((await bugs.listBugs(parse({ q: `bug-${bug2}` }))).items.map((i) => i.number), [bug2], 'by key');
  assert.deepEqual((await bugs.listBugs(parse({ q: 'partial payment' }))).items.map((i) => i.number), [bug1], 'by title');
  assert.deepEqual((await bugs.listBugs(parse({ q: 'balance shows' }))).items.map((i) => i.number), [bug1], 'by the results');
  assert.deepEqual((await bugs.listBugs(parse({ severity: 'CRITICAL,MAJOR' }))).items.map((i) => i.number), [bug1]);
  assert.deepEqual((await bugs.listBugs(parse({ app: 'ANDROID_APP' }))).items.map((i) => i.number), [bug2]);
  assert.deepEqual((await bugs.listBugs(parse({ assigneeId: 'none' }))).items.map((i) => i.number), [bug2]);
  assert.deepEqual((await bugs.listBugs(parse({ assigneeId: dev.id }))).items.map((i) => i.number), [bug1]);
  assert.deepEqual((await bugs.listBugs(parse({ reporterId: qa2.id }))).items.map((i) => i.number), [bug2]);
  assert.deepEqual((await bugs.listBugs(parse({ priority: 'NONE' }))).items.map((i) => i.number), [bug2], 'not triaged');
  assert.deepEqual((await bugs.listBugs(parse({ tenantKind: 'PG', moduleId: billingId }))).items.map((i) => i.number), [bug1]);
  assert.equal((await bugs.listBugs(parse({ status: 'CLOSED' }))).total, 0);
  // Severity sorts by what it means: critical before minor.
  assert.deepEqual((await bugs.listBugs(parse({ sort: 'severity' }))).items.map((i) => i.severity), ['CRITICAL', 'MINOR']);
  assert.deepEqual((await bugs.listBugs(parse({ sort: 'priority' }))).items.map((i) => i.priority), ['P1', null], 'untriaged last');
  assert.deepEqual((await bugs.listBugs(parse({ sort: 'oldest', limit: 1 }))).items.map((i) => i.number), [bug1]);
  assert.equal((await bugs.listBugs(parse({ sort: 'oldest', limit: 1 }))).hasMore, true);
  assert.throws(() => parse({ status: 'OPEN,NOPE' }), /Unknown filter/);
  assert.equal(bugNumberFrom('BUG-12'), 12);
  assert.equal(bugNumberFrom('#7'), 7);
  assert.equal(bugNumberFrom('twelve'), null);
});

test('bugs similar: open bugs with the same words in the title', async () => {
  const hits = await bugs.similarBugs('Wrong invoice total when a payment is partial');
  assert.deepEqual(hits.items.map((i) => i.number), [bug1]);
  assert.equal((await bugs.similarBugs('Wrong invoice total when a payment is partial', bug1)).items.length, 0, 'not itself, when editing');
  assert.equal((await bugs.similarBugs('Gate pass QR does not scan')).items.length, 0);
  assert.equal((await bugs.similarBugs('the and')).items.length, 0);
});

let commentId = '';

test('bugs comments: mentions bring people in; only the author edits; the author or super admin removes', async () => {
  const shot = await files.uploadFile({ body: png(), filename: 'after-fix.png' }, dev);
  const outsider = hostelAdminId;
  const b = await bugs.addComment(bug2, commentSchema.parse({ body: 'Can you check this, @Bina QA? Works for me.', mentionIds: [qa2.id, outsider], attachmentIds: [shot.id] }), dev);
  const c = b.comments[0];
  commentId = c.id;
  assert.equal(c.author?.name, 'Dev Kumar');
  assert.deepEqual(c.mentions.map((m) => m!.name), ['Bina QA'], 'a hostel account can’t be mentioned');
  assert.equal(c.files[0].filename, 'after-fix.png');
  assert.ok(b.watchers.some((w) => w!.id === dev.id) && b.watchers.some((w) => w!.id === qa2.id));
  assert.ok(b.lastActivityAt > (await raw.bug.findUniqueOrThrow({ where: { number: bug2 } })).createdAt);
  assert.equal((await bugs.listBugs(listBugsSchema.parse({ q: `BUG-${bug2}` }))).items[0].commentCount, 1);

  await assert.rejects(() => bugs.editComment(commentId, editCommentSchema.parse({ body: 'Rewritten by someone else' }), qa2), /author/);
  const edited = await bugs.editComment(commentId, editCommentSchema.parse({ body: 'Works for me on 1.4.2.' }), dev);
  assert.ok(edited.comments[0].editedAt);
  assert.deepEqual(edited.comments[0].mentions, []);
  assert.throws(() => commentSchema.parse({ body: '   ' }), /required/);

  await assert.rejects(() => bugs.deleteComment(commentId, qa2), /author/);
  const fileKey = (await raw.bugAttachment.findFirstOrThrow({ where: { commentId } })).key;
  const removed = await bugs.deleteComment(commentId, admin);
  assert.equal(removed.comments[0].deleted, true);
  assert.equal(removed.comments[0].body, '');
  assert.ok(!stored.has(fileKey), 'its file goes with it');
  await assert.rejects(() => bugs.editComment(commentId, editCommentSchema.parse({ body: 'Back again' }), dev), /not found/);
});

test('bugs files: more can be added; only the uploader or the super admin removes one; ten at most', async () => {
  const extra = await files.uploadFile({ body: png(), filename: 'second.png' }, qa2);
  const withExtra = await bugs.addFiles(bug1, [extra.id], qa2);
  assert.equal(withExtra.files.length, 3);
  assert.equal(withExtra.events[withExtra.events.length - 1].type, 'FILE_ADDED');
  await assert.rejects(() => bugs.deleteFile(extra.id, qa), /person who attached/);
  await bugs.deleteFile(extra.id, qa2);
  const after = await bugs.getBug(bug1, qa);
  assert.equal(after.files.length, 2);
  assert.deepEqual((after.events[after.events.length - 1].changes as { files: string[] }).files, ['second.png']);
  await bugs.deleteFile(after.files[1].id, admin);

  const many: string[] = [];
  for (let i = 0; i < 10; i++) many.push((await files.uploadFile({ body: png(), filename: `f${i}.png` }, qa)).id);
  await assert.rejects(() => bugs.addFiles(bug1, many, qa), /at most 10/);
  // Never attached: gone once they are a day old, and only those.
  assert.equal(await files.purgeUnattached(), 0, 'not yet');
  await raw.bugAttachment.updateMany({ where: { id: { in: many } }, data: { createdAt: new Date(Date.now() - 25 * 3_600_000) } });
  assert.equal(await files.purgeUnattached(), 10);
  assert.equal((await bugs.getBug(bug1, qa)).files.length, 1, 'attached files are never purged');
});

test('bugs links and watching', async () => {
  const linked = await bugs.linkRelated(bug1, bug2, qa);
  assert.deepEqual(linked.links.map((l) => [l.kind, l.bug.key]), [['RELATED', `BUG-${bug2}`]]);
  assert.deepEqual((await bugs.getBug(bug2, qa)).links.map((l) => l.bug.key), [`BUG-${bug1}`], 'seen from the other bug too');
  await assert.rejects(() => bugs.linkRelated(bug2, bug1, qa), ConflictError);
  await assert.rejects(() => bugs.linkRelated(bug1, bug1, qa), /itself/);
  await assert.rejects(() => bugs.linkRelated(bug1, 999_999, qa), NotFoundError);
  const unlinked = await bugs.unlink(bug2, linked.links[0].id, dev);
  assert.equal(unlinked.links.length, 0);

  assert.equal((await bugs.setWatching(bug1, false, qa)).watching, false);
  assert.equal((await bugs.setWatching(bug1, true, qa2)).watching, true);
  await assert.rejects(() => bugs.getBug(999_999, qa), NotFoundError);
});

// ── BT3: the fix-and-verify loop ───────────────────────────────────────────

test('bugs workflow: who may do what, from every status', () => {
  const reporter = 'reporter-id';
  const people = { QA: { id: 'q', role: Role.QA }, REPORTER: { id: reporter, role: Role.QA }, DEV: { id: 'd', role: Role.DEVELOPER }, ADMIN: { id: 'a', role: Role.SUPER_ADMIN } };
  const can = (who: keyof typeof people, status: string) => allowedActions(people[who], { status: status as never, reporterId: reporter }).join(',');
  // A developer works a bug; never closes or reopens it.
  assert.equal(can('DEV', 'OPEN'), 'start,ask,fix,suggest');
  assert.equal(can('DEV', 'IN_PROGRESS'), 'ask,fix,suggest');
  assert.equal(can('DEV', 'REOPENED'), 'start,ask,fix,suggest');
  assert.equal(can('DEV', 'NEEDS_INFO'), 'start,fix,suggest');
  assert.equal(can('DEV', 'FIXED'), '');
  assert.equal(can('DEV', 'CLOSED'), '');
  // QA closes and reopens; never marks a bug fixed.
  assert.equal(can('QA', 'OPEN'), 'close');
  assert.equal(can('QA', 'IN_PROGRESS'), 'close');
  assert.equal(can('QA', 'NEEDS_INFO'), 'answer,close');
  assert.equal(can('QA', 'FIXED'), 'close,reopen');
  assert.equal(can('QA', 'CLOSED'), 'reopen');
  // The super admin can do either side.
  assert.equal(can('ADMIN', 'OPEN'), 'start,ask,fix,suggest,close');
  assert.equal(can('ADMIN', 'FIXED'), 'close,reopen');
  assert.equal(can('ADMIN', 'CLOSED'), 'reopen');
  // A developer who reported a bug can answer a question about it, and still not close it.
  assert.equal(allowedActions({ id: reporter, role: Role.DEVELOPER }, { status: 'NEEDS_INFO' as never, reporterId: reporter }).join(','), 'start,fix,suggest,answer');
});

let wf = 0; // the bug this loop is walked on

test('bugs workflow: start → ask → answer → fix → reopen → fix → verified', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const b = await bugs.createBug(report({ title: 'Workflow walk: gate pass QR does not scan', moduleId: mess }), qa);
  wf = b.number;
  assert.equal(b.assignee, null);
  assert.deepEqual(b.can.actions, ['close'], 'a tester can only close a new bug (with a reason)');
  assert.deepEqual((await bugs.getBug(wf, dev)).can.actions, ['start', 'ask', 'fix', 'suggest']);

  // A tester can't start or fix; a developer can't close.
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'start' }), qa), /role/);
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'close', resolution: 'NOT_A_BUG' }), dev), /Only QA or the super admin/);

  const started = await workflow.moveBug(wf, moveSchema.parse({ action: 'start' }), dev);
  assert.equal(started.status, 'IN_PROGRESS');
  assert.equal(started.assignee?.name, 'Dev Kumar', 'the developer who starts it takes it');
  const ev = started.events[started.events.length - 1];
  assert.equal(ev.type, 'STATUS');
  assert.deepEqual((ev.changes as Record<string, unknown>).status, { from: 'OPEN', to: 'IN_PROGRESS' });

  assert.throws(() => moveSchema.parse({ action: 'ask', note: 'why' }), /at least 5/);
  const asked = await workflow.moveBug(wf, moveSchema.parse({ action: 'ask', note: 'Which phone and Android version?' }), dev);
  assert.equal(asked.status, 'NEEDS_INFO');
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'ask', note: 'Asking again' }), dev), /waiting for information/);
  const answered = await workflow.moveBug(wf, moveSchema.parse({ action: 'answer', note: 'Samsung S22, Android 14.' }), qa);
  assert.equal(answered.status, 'OPEN');
  assert.equal((answered.events[answered.events.length - 1].changes as { note: string }).note, 'Samsung S22, Android 14.');

  // Fixed needs its note; the link must be https.
  assert.throws(() => moveSchema.parse({ action: 'fix' }), /Required/);
  assert.throws(() => moveSchema.parse({ action: 'fix', note: 'Fixed the scanner', fixLink: 'http://github.com/x' }), /https/);
  const fixed = await workflow.moveBug(wf, moveSchema.parse({ action: 'fix', note: 'The scanner ignored dark-mode QR codes.', fixLink: 'https://github.com/x/pull/9', fixedIn: 'Android 1.4.3' }), dev);
  assert.equal(fixed.status, 'FIXED');
  assert.equal(fixed.resolution, null);
  assert.equal(fixed.fixNote, 'The scanner ignored dark-mode QR codes.');
  assert.equal(fixed.fixedIn, 'Android 1.4.3');
  assert.deepEqual(fixed.can.actions, [], 'the developer now waits for QA');
  assert.deepEqual((await bugs.getBug(wf, qa)).can.actions, ['close', 'reopen']);

  // QA: still broken. It goes back to the same developer, and the count is kept.
  assert.throws(() => moveSchema.parse({ action: 'reopen' }), /Required/);
  const reopened = await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'Still fails on a cracked screen.' }), qa2);
  assert.equal(reopened.status, 'REOPENED');
  assert.equal(reopened.reopenCount, 1);
  assert.equal(reopened.assignee?.name, 'Dev Kumar');

  await workflow.moveBug(wf, moveSchema.parse({ action: 'fix', note: 'Raised the scanner’s contrast threshold.' }), dev);
  const closed = await workflow.moveBug(wf, moveSchema.parse({ action: 'close', note: 'Works on three phones.' }), qa);
  assert.equal(closed.status, 'CLOSED');
  assert.equal(closed.resolution, 'VERIFIED', 'closing a fix with no reason means it is verified');
  assert.ok(closed.closedAt);
  assert.deepEqual(closed.can.actions, ['reopen']);
  assert.equal(closed.can.assign, false);
  assert.ok(closed.watchers.some((w) => w!.id === qa2.id), 'whoever moves a bug follows it');

  // Closed: nothing but reopening, and only by QA or the super admin.
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'start' }), dev), /closed/);
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'I want it back' }), dev), /Only QA or the super admin/);
  const again = await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'Broke again in 1.4.4.' }), admin);
  assert.equal(again.reopenCount, 2);
  assert.equal(again.resolution, null);
  assert.equal(again.closedAt, null);
});

test('bugs workflow: a developer suggests a reason; QA agrees or disagrees', async () => {
  // Not a bug: QA agrees by closing with no reason of their own.
  const s1 = await workflow.moveBug(wf, moveSchema.parse({ action: 'suggest', resolution: 'NOT_A_BUG', note: 'The pass had expired; the message says so.' }), dev);
  assert.equal(s1.status, 'FIXED');
  assert.equal(s1.resolution, 'NOT_A_BUG', 'waiting for QA with the suggested reason');
  assert.throws(() => moveSchema.parse({ action: 'suggest', resolution: 'VERIFIED', note: 'It is fine now' }), /Invalid enum/);
  const agreed = await workflow.moveBug(wf, moveSchema.parse({ action: 'close' }), qa);
  assert.equal(agreed.resolution, 'NOT_A_BUG');

  // Duplicate: needs the original, links the two, and can't loop.
  await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'It is a bug: the pass was valid.' }), qa);
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'suggest', resolution: 'DUPLICATE', note: 'Same as another one' }), dev), /which bug/);
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'suggest', resolution: 'DUPLICATE', note: 'Same as itself', duplicateOf: wf }), dev), /itself/);
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'suggest', resolution: 'DUPLICATE', note: 'Same as nothing', duplicateOf: 999_999 }), dev), NotFoundError);
  const dup = await workflow.moveBug(wf, moveSchema.parse({ action: 'suggest', resolution: 'DUPLICATE', note: 'Same cause as the mess one.', duplicateOf: `BUG-${bug2}` }), dev);
  assert.deepEqual(dup.links.map((l) => [l.kind, l.direction, l.bug.number]), [['DUPLICATE', 'out', bug2]]);
  assert.deepEqual((await bugs.getBug(bug2, qa)).links.map((l) => [l.kind, l.direction, l.bug.number]), [['DUPLICATE', 'in', wf]]);
  await assert.rejects(() => workflow.moveBug(bug2, moveSchema.parse({ action: 'close', resolution: 'DUPLICATE', duplicateOf: wf }), qa), /already marked as a duplicate of this bug/);

  // QA disagrees: reopening removes the duplicate link.
  const back = await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'Different cause: this one is the camera.' }), qa);
  assert.equal(back.links.length, 0);
  assert.equal(back.reopenCount, 4);

  // QA closes an open bug with a reason of their own; without one it is refused.
  await assert.rejects(() => workflow.moveBug(wf, moveSchema.parse({ action: 'close' }), qa), /Say why/);
  const wontFix = await workflow.moveBug(wf, moveSchema.parse({ action: 'close', resolution: 'WONT_FIX', note: 'The old scanner is being replaced.' }), qa);
  assert.equal(wontFix.resolution, 'WONT_FIX');
  await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'The replacement slipped; fix it after all.' }), qa);
});

test('bugs workflow: two people pressing at once make one move', async () => {
  const results = await Promise.allSettled([
    workflow.moveBug(wf, moveSchema.parse({ action: 'fix', note: 'Fixed by the first click.' }), dev),
    workflow.moveBug(wf, moveSchema.parse({ action: 'fix', note: 'Fixed by the second click.' }), admin),
  ]);
  assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1);
  const lost = results.find((r) => r.status === 'rejected') as PromiseRejectedResult;
  assert.match(String(lost.reason?.message), /Someone else just changed this bug|waiting for QA/);
  assert.equal((await bugs.getBug(wf, qa)).status, 'FIXED');
  await workflow.moveBug(wf, moveSchema.parse({ action: 'reopen', note: 'Back to open for the next tests.' }), qa);
});

test('bugs assign: to a switched-on developer only; anyone on the tracker; not once closed', async () => {
  const dev2 = (await team.createMember({ name: 'Second Dev', email: 'dev2@bugs.test', role: Role.DEVELOPER }, admin)).member;
  const a = await workflow.assignBug(wf, dev2.id, qa);
  assert.equal(a.assignee?.name, 'Second Dev');
  const ev = a.events[a.events.length - 1];
  assert.equal(ev.type, 'ASSIGNED');
  assert.deepEqual((ev.changes as Record<string, unknown>).assignee, { from: dev.id, to: dev2.id });
  assert.ok(a.watchers.some((w) => w!.id === dev2.id), 'the new assignee follows it');
  // Assigning to the same person again records nothing.
  assert.equal((await workflow.assignBug(wf, dev2.id, qa)).events.length, a.events.length);
  // A developer passes it on, or takes it; nobody assigns to a tester, a hostel account or a switched-off developer.
  assert.equal((await workflow.assignBug(wf, dev.id, { id: dev2.id, name: 'Second Dev', role: Role.DEVELOPER })).assignee?.id, dev.id);
  for (const bad of [qa.id, hostelAdminId, admin.id]) await assert.rejects(() => workflow.assignBug(wf, bad, qa), /developer/);
  await team.deactivateMember(dev2.id);
  await assert.rejects(() => workflow.assignBug(wf, dev2.id, qa), /switched on/);
  assert.equal((await workflow.assignBug(wf, null, qa)).assignee, null, 'back to unassigned');
  // A developer fixing an unassigned bug owns the fix.
  const fixed = await workflow.moveBug(wf, moveSchema.parse({ action: 'fix', note: 'Fixed while unassigned.' }), dev);
  assert.equal(fixed.assignee?.id, dev.id);
  await workflow.moveBug(wf, moveSchema.parse({ action: 'close' }), qa);
  await assert.rejects(() => workflow.assignBug(wf, dev.id, qa), /closed/);
});

test('bugs bulk: each bug follows the same rules and reports its own result', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const a = (await bugs.createBug(report({ title: 'Bulk one: menu photo is stretched', moduleId: mess }), qa)).number;
  const b = (await bugs.createBug(report({ title: 'Bulk two: menu photo is stretched on tablets', moduleId: mess }), qa)).number;

  const assigned = await workflow.bulk(bulkSchema.parse({ action: 'assign', numbers: [a, b, wf, 999_999], assigneeId: dev.id }), qa);
  assert.deepEqual(assigned.done, [a, b]);
  assert.deepEqual(assigned.failed.map((f) => [f.number, /closed|not found/.test(f.message)]), [[wf, true], [999_999, true]]);

  const prio = await workflow.bulk(bulkSchema.parse({ action: 'priority', numbers: [a, b], priority: 'P2' }), dev);
  assert.deepEqual(prio.done, [a, b]);
  assert.equal((await bugs.getBug(a, qa)).priority, 'P2');
  // The closed bug: another tester can't change it, as when editing one at a time.
  assert.equal((await workflow.bulk(bulkSchema.parse({ action: 'priority', numbers: [wf], priority: 'P1' }), qa2)).failed.length, 1);

  // Closing as duplicates is QA's; a developer's attempt fails on every bug.
  assert.equal((await workflow.bulk(bulkSchema.parse({ action: 'duplicate', numbers: [b], duplicateOf: a }), dev)).failed.length, 1);
  const dup = await workflow.bulk(bulkSchema.parse({ action: 'duplicate', numbers: [b, a], duplicateOf: `BUG-${a}` }), qa);
  assert.deepEqual(dup.done, [b]);
  assert.match(dup.failed[0].message, /itself/);
  const closed = await bugs.getBug(b, qa);
  assert.equal(closed.status, 'CLOSED');
  assert.equal(closed.resolution, 'DUPLICATE');
  assert.equal(closed.links[0].bug.number, a);
  assert.throws(() => bulkSchema.parse({ action: 'assign', numbers: [], assigneeId: null }), /at least 1/);
  assert.throws(() => bulkSchema.parse({ action: 'delete', numbers: [a] }), /Invalid discriminator/);
});

test('bugs my work: each role sees what waits on them', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const fresh = (await bugs.createBug(report({ title: 'My work: notice board is blank', moduleId: mess }), qa)).number;
  const d = await workflow.myWork(dev);
  assert.deepEqual(d.groups.map((g) => g.key), ['reopened', 'assigned', 'waiting', 'unassigned', 'for-qa']);
  const unassignedBefore = d.groups.find((g) => g.key === 'unassigned')!;
  assert.ok(unassignedBefore.items.some((i) => i.number === fresh));
  assert.equal(d.attention, d.groups.filter((g) => g.attention).reduce((n, g) => n + g.count, 0));
  assert.equal(await workflow.attentionCount(dev), d.attention);

  // The developer takes it and asks; it moves to the tester's "needs my answer".
  await workflow.moveBug(fresh, moveSchema.parse({ action: 'start' }), dev);
  assert.ok((await workflow.myWork(dev)).groups.find((g) => g.key === 'assigned')!.items.some((i) => i.number === fresh));
  await workflow.moveBug(fresh, moveSchema.parse({ action: 'ask', note: 'Which hostel type?' }), dev);
  const q = await workflow.myWork(qa);
  assert.deepEqual(q.groups.map((g) => g.key), ['to-verify', 'not-deployed', 'needs-answer', 'reported']);
  assert.ok(q.groups.find((g) => g.key === 'needs-answer')!.items.some((i) => i.number === fresh));
  assert.ok(!(await workflow.myWork(qa2)).groups.find((g) => g.key === 'needs-answer')!.items.some((i) => i.number === fresh), 'only its reporter is asked');

  // Fixed: every tester sees it to verify; the developer sees it waiting.
  await workflow.moveBug(fresh, moveSchema.parse({ action: 'fix', note: 'Notices are loaded again.' }), dev);
  for (const who of [qa, qa2]) assert.ok((await workflow.myWork(who)).groups.find((g) => g.key === 'to-verify')!.items.some((i) => i.number === fresh));
  assert.ok((await workflow.myWork(dev)).groups.find((g) => g.key === 'for-qa')!.items.some((i) => i.number === fresh));
  // A group's filters find the same bugs on the list.
  const group = (await workflow.myWork(qa)).groups.find((g) => g.key === 'to-verify')!;
  assert.equal((await bugs.listBugs(listBugsSchema.parse(group.filters))).total, group.count);
  assert.deepEqual((await workflow.myWork(admin)).groups.map((g) => g.key), ['unassigned', 'to-verify', 'reopened', 'needs-info', 'untriaged']);
});

// ── BT4: notifications, the dashboard, the export, the Monday summary ───────

const mine = (who: BugActor) => raw.bugNotification.findMany({ where: { userId: who.id }, orderBy: { createdAt: 'asc' } });
const emailOf = async (who: BugActor) => (await raw.user.findUniqueOrThrow({ where: { id: who.id } })).email;
let noted = 0;

test('bugs notify: one notification per event per person, never to the one who did it', async () => {
  await notes.settle();
  await raw.bugNotification.deleteMany({});
  sent.length = 0;

  // A new bug in a module with a developer: the developer is told; the reporter is not.
  noted = (await bugs.createBug(report({ title: 'Notify: receipt shows the wrong month', actual: 'The receipt says October for a November payment.' }), qa)).number;
  await notes.settle();
  assert.deepEqual((await mine(dev)).map((n) => n.kind), ['NEW_ASSIGNED']);
  assert.equal((await mine(qa)).length, 0);
  assert.deepEqual(sent.map((m) => m.to), [await emailOf(dev)]);
  assert.match(sent[0].subject, new RegExp(`^\\[BUG-${noted}\\] New bug for you · Notify: receipt`));
  assert.match(sent[0].text, new RegExp(`/bugs#bugs/${noted}`));
  assert.match(sent[0].text, /Asha QA reported BUG-\d+, and it came to you/);

  // A comment that calls someone in: they are "mentioned", the people already on it get "a comment".
  sent.length = 0;
  await bugs.addComment(noted, commentSchema.parse({ body: 'Same on the PDF. @Platform Owner please look.', mentionIds: [admin.id, qa2.id] }), qa2);
  await notes.settle();
  assert.deepEqual((await mine(admin)).map((n) => n.kind), ['MENTION']);
  assert.deepEqual((await mine(qa)).map((n) => n.kind), ['COMMENT']);
  assert.deepEqual((await mine(dev)).map((n) => n.kind), ['NEW_ASSIGNED', 'COMMENT']);
  assert.equal((await mine(qa2)).length, 0, 'not told about their own comment, even when they mention themselves');
  assert.equal(sent.length, 3);
  assert.ok(sent.some((m) => /You were mentioned/.test(m.subject)) && sent.filter((m) => /New comment/.test(m.subject)).length === 2);
  assert.ok(sent.every((m) => m.text.includes('Same on the PDF')));

  // An edit tells only the people it newly calls in.
  sent.length = 0;
  const comment = (await bugs.getBug(noted, qa2)).comments.at(-1)!;
  await bugs.editComment(comment.id, editCommentSchema.parse({ body: 'Same on the PDF. Asking the team.', mentionIds: [admin.id, qa.id] }), qa2);
  await notes.settle();
  assert.deepEqual(sent.map((m) => m.to), [await emailOf(qa)]);

  // A move tells everyone on the bug but its doer. Starting work is not news.
  sent.length = 0;
  await workflow.moveBug(noted, moveSchema.parse({ action: 'start' }), dev);
  await workflow.moveBug(noted, moveSchema.parse({ action: 'ask', note: 'Which payment mode was it?' }), dev);
  await notes.settle();
  assert.equal(sent.length, 3);
  assert.ok(sent.every((m) => /Question/.test(m.subject) && m.text.includes('Which payment mode')));
  assert.equal((await mine(dev)).length, 2);
  for (const who of [qa, qa2, admin]) assert.equal((await mine(who)).at(-1)!.kind, 'ASKED');
  assert.ok((await raw.bugNotification.findMany({})).every((n) => n.emailStatus === 'DRY_RUN'), 'each email is recorded as handed over');

  // What the bell shows.
  const bell = await notes.listNotifications(qa, { page: 1, limit: 25, unread: false });
  assert.equal(bell.items[0].text, `Dev Kumar asked a question on BUG-${noted}`);
  assert.equal(bell.items[0].snippet, 'Which payment mode was it?');
  assert.equal(bell.items[0].bug.title, 'Notify: receipt shows the wrong month');
  assert.equal(bell.unread, bell.total);
});

test('bugs notify: each person’s email switches; nothing to a switched-off account', async () => {
  const before = await notes.getPrefs(qa);
  assert.deepEqual(before.switches.map((x) => x.key), ['ASSIGNED', 'STATUS', 'COMMENT', 'MENTION']);
  assert.ok(before.switches.every((x) => x.on), 'everything is on until switched off (D7)');
  assert.ok((await notes.getPrefs(admin)).switches.some((x) => x.key === 'WEEKLY'), 'the super admin also has the Monday summary');
  // A tester has no weekly summary to switch.
  const after = await notes.setPrefs(qa, ['STATUS', 'WEEKLY']);
  assert.deepEqual(after.switches.filter((x) => !x.on).map((x) => x.key), ['STATUS']);

  // Status news still reaches the bell, but not the inbox; the others are unaffected.
  sent.length = 0;
  await workflow.moveBug(noted, moveSchema.parse({ action: 'answer', note: 'It was UPI.' }), qa2);
  await workflow.moveBug(noted, moveSchema.parse({ action: 'fix', note: 'The receipt uses the payment date now.', fixedIn: 'web 1.42' }), dev);
  await notes.settle();
  const asha = await mine(qa);
  assert.deepEqual(asha.slice(-2).map((n) => [n.kind, n.emailStatus]), [['ANSWERED', 'NONE'], ['FIXED', 'NONE']]);
  assert.ok(!sent.some((m) => m.to === 'asha@bugs.test'));
  assert.ok(sent.some((m) => m.to === 'bina@bugs.test' && /\] Fixed · /.test(m.subject)));
  // A comment is another switch, still on.
  sent.length = 0;
  await bugs.addComment(noted, commentSchema.parse({ body: 'Checking on staging now.' }), qa2);
  await notes.settle();
  assert.ok(sent.some((m) => m.to === 'asha@bugs.test'));
  await notes.setPrefs(qa, []);

  // A follower whose account is switched off is told nothing, in the bell or by email.
  const gone = (await team.createMember({ name: 'Gone Dev', email: 'gone@bugs.test', role: Role.DEVELOPER }, admin)).member;
  const goneActor: BugActor = { id: gone.id, name: gone.name, role: Role.DEVELOPER };
  await bugs.setWatching(noted, true, goneActor);
  await team.deactivateMember(gone.id);
  sent.length = 0;
  await bugs.addComment(noted, commentSchema.parse({ body: 'One more check.' }), qa);
  await notes.settle();
  assert.equal((await mine(goneActor)).length, 0);
  assert.ok(!sent.some((m) => m.to === 'gone@bugs.test'));

  // The job's sweep: an email a restart left unsent goes out; one for an account switched off since does not.
  const bugId = (await raw.bug.findUniqueOrThrow({ where: { number: noted } })).id;
  const old = new Date(Date.now() - 10 * 60_000);
  await raw.bugNotification.createMany({
    data: [
      { userId: qa2.id, bugId, actorId: dev.id, kind: 'REOPENED', group: 'STATUS', emailStatus: 'PENDING', createdAt: old },
      { userId: gone.id, bugId, actorId: dev.id, kind: 'COMMENT', group: 'COMMENT', emailStatus: 'PENDING', createdAt: old },
      { userId: qa.id, bugId, actorId: dev.id, kind: 'COMMENT', group: 'COMMENT', emailStatus: 'PENDING' },
    ],
  });
  sent.length = 0;
  assert.equal(await notes.sendLeftovers(), 2);
  assert.deepEqual(sent.map((m) => m.to), ['bina@bugs.test']);
  assert.equal((await mine(goneActor))[0].emailStatus, 'NONE');
  assert.equal((await mine(qa)).at(-1)!.emailStatus, 'PENDING', 'a fresh one is left to the request that made it');
  assert.equal(await notes.sendLeftovers(), 0, 'and nothing goes twice');
  await raw.bugNotification.updateMany({ where: { emailStatus: 'PENDING' }, data: { emailStatus: 'NONE' } });
});

test('bugs notify: the bell: unread, read on its own, and all at once', async () => {
  const unread = await notes.unreadCount(qa);
  assert.ok(unread >= 3);
  const list = await notes.listNotifications(qa, { page: 1, limit: 2, unread: true });
  assert.equal(list.items.length, 2);
  assert.equal(list.hasMore, true);
  assert.ok(list.items.every((i) => !i.read));
  // Mine only: another person's notification can't be marked by me.
  const theirs = (await mine(qa2))[0];
  assert.equal((await notes.markRead(qa, { ids: [theirs.id] })).unread, unread);
  assert.equal((await raw.bugNotification.findUniqueOrThrow({ where: { id: theirs.id } })).readAt, null);
  assert.equal((await notes.markRead(qa, { ids: [list.items[0].id] })).unread, unread - 1);
  assert.equal((await notes.markRead(qa, { all: true })).unread, 0);
  assert.equal((await notes.listNotifications(qa, { page: 1, limit: 25, unread: true })).total, 0);
  assert.ok((await notes.listNotifications(qa, { page: 1, limit: 25, unread: false })).items.every((i) => i.read));

  // Opening a bug reads what I was told about it.
  const bugId = (await raw.bug.findUniqueOrThrow({ where: { number: noted } })).id;
  assert.ok((await notes.unreadCount(dev)) > 0);
  await notes.markBugRead(dev, bugId);
  assert.equal(await raw.bugNotification.count({ where: { userId: dev.id, bugId, readAt: null } }), 0);
});

test('bugs notify: a bulk change is one email per person', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const many: number[] = [];
  for (const t of ['Bulk mail: menu repeats', 'Bulk mail: tokens count twice', 'Bulk mail: feedback form blank']) {
    many.push((await bugs.createBug(report({ title: t, moduleId: mess, actual: `${t} on the mess page.` }), qa)).number);
  }
  await notes.settle();
  sent.length = 0;
  const before = (await mine(dev)).length;
  await workflow.bulk(bulkSchema.parse({ action: 'assign', numbers: many, assigneeId: dev.id }), qa);
  await notes.settle();
  assert.equal(sent.length, 1);
  assert.equal(sent[0].to, 'devk@bugs.test');
  assert.equal(sent[0].subject, 'Asha QA assigned 3 bugs to you');
  for (const n of many) assert.ok(sent[0].text.includes(`BUG-${n}`));
  const rows = (await mine(dev)).slice(before);
  assert.deepEqual(rows.map((r) => [r.kind, r.emailStatus]), [['ASSIGNED', 'DRY_RUN'], ['ASSIGNED', 'DRY_RUN'], ['ASSIGNED', 'DRY_RUN']], 'three in the bell, one in the inbox');

  // One bug in a bulk change is an ordinary email.
  sent.length = 0;
  await workflow.bulk(bulkSchema.parse({ action: 'assign', numbers: [many[0]], assigneeId: null }), qa);
  await workflow.bulk(bulkSchema.parse({ action: 'assign', numbers: [many[0]], assigneeId: dev.id }), qa);
  await notes.settle();
  assert.equal(sent.length, 1);
  assert.match(sent[0].subject, new RegExp(`^\\[BUG-${many[0]}\\] Assigned to you`));
});

test('bugs dashboard: the tiles match the list; the super admin also sees developers and how fixes hold', async () => {
  // Monday 00:00 India time starts the week.
  assert.equal(insights.weekStart(new Date('2026-11-18T04:30:00Z')).toISOString(), '2026-11-15T18:30:00.000Z');
  assert.equal(insights.weekStart(new Date('2026-11-22T17:30:00Z')).toISOString(), '2026-11-15T18:30:00.000Z', 'Sunday night is still that week');
  assert.equal(insights.weekStart(new Date('2026-11-15T18:40:00Z')).toISOString(), '2026-11-15T18:30:00.000Z', 'ten past midnight on Monday');

  // One bug reported 40 days ago, still open.
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const aged = (await bugs.createBug(report({ title: 'Dashboard: an old one', moduleId: mess, actual: 'Reported long ago and never fixed.', severity: 'CRITICAL' }), qa)).number;
  await raw.bug.update({ where: { number: aged }, data: { createdAt: new Date(Date.now() - 40 * 86_400_000) } });

  const d = await insights.dashboard(admin);
  assert.equal(d.full, true);
  assert.deepEqual(d.tiles.map((t) => t.key), ['open', 'unassigned', 'waiting-for-qa', 'reopened', 'critical', 'older-7', 'older-30']);
  // Every number opens the same bugs on the list.
  for (const t of d.tiles) assert.equal((await bugs.listBugs(listBugsSchema.parse(t.filters))).total, t.count, t.key);
  const tile = (k: string) => d.tiles.find((t) => t.key === k)!.count;
  assert.equal(tile('older-30'), 1);
  assert.equal(tile('older-7'), 1);
  assert.ok(tile('critical') >= 1 && tile('open') > tile('waiting-for-qa'));
  assert.equal(d.bySeverity.reduce((n, s) => n + s.count, 0), tile('open'));
  assert.deepEqual(d.bySeverity.map((s) => s.severity), ['CRITICAL', 'MAJOR', 'MINOR', 'TRIVIAL']);
  assert.equal(d.byModule.reduce((n, m) => n + m.count, 0), tile('open'));
  for (const m of d.byModule) assert.equal((await bugs.listBugs(listBugsSchema.parse(m.filters))).total, m.count);

  // Eight weeks, oldest first; everything else in this test run was reported this week.
  assert.equal(d.weeks.length, 8);
  assert.equal(d.weeks.at(-1)!.opened + d.weeks.slice(0, -1).reduce((n, w) => n + w.opened, 0), await raw.bug.count({ where: { createdAt: { gte: new Date(insights.weekStart(new Date()).getTime() - 7 * 7 * 86_400_000) } } }));
  assert.equal(d.weeks.reduce((n, w) => n + w.closed, 0), await raw.bug.count({ where: { status: 'CLOSED' } }));

  // How each developer stands, and how fixes held.
  assert.ok(d.developers && d.quality);
  const kumar = d.developers!.find((x) => x.name === 'Dev Kumar')!;
  assert.equal(kumar.toFix + kumar.reopened + kumar.waitingForQa, await raw.bug.count({ where: { assigneeId: dev.id, status: { not: 'CLOSED' } } }));
  assert.ok(kumar.fixed >= 2 && kumar.sentBack >= 1, 'BT3’s walk fixed a bug twice and QA sent it back once');
  assert.ok(!d.developers!.some((x) => x.name === 'Gone Dev'), 'a switched-off developer with no bugs is left out');
  assert.equal(d.quality!.days, 90);
  assert.ok(d.quality!.fixed >= 2 && d.quality!.sentBack >= 1);
  assert.equal(d.quality!.reopenRate, Math.round((d.quality!.sentBack / d.quality!.fixed) * 1000) / 1000);
  assert.ok(d.quality!.avgFixHours !== null && d.quality!.avgFixHours >= 0);
  assert.ok(d.quality!.avgVerifyHours !== null, 'a verified fix gives a time to verify');

  // The team's version: where the bugs stand, not who did what.
  const short = await insights.dashboard(qa);
  assert.equal(short.full, false);
  assert.deepEqual(short.tiles, d.tiles);
  assert.ok(!('developers' in short) && !('quality' in short));
});

test('bugs export: the list as filtered, as an Excel file', async () => {
  const closed = listBugsSchema.parse({ status: 'CLOSED' });
  const file = await insights.exportBugs(closed, new Date('2026-11-16T06:00:00Z'));
  assert.equal(file.filename, 'hostelcare-bugs-2026-11-16.xlsx');
  assert.equal(file.bytes.subarray(0, 2).toString(), 'PK', 'an .xlsx is a zip');
  assert.equal(file.count, (await bugs.listBugs(closed)).total);
  const all = await insights.exportBugs(listBugsSchema.parse({}));
  assert.equal(all.count, await raw.bug.count());
  assert.ok(all.bytes.length > file.bytes.length);
  assert.throws(() => listBugsSchema.parse({ olderThan: '0' }));
});

test('bugs weekly summary: Monday morning, once, to the super admins who want it', async () => {
  const monday = insights.weekStart(new Date()).getTime() + 7 * 86_400_000;
  const at = (hours: number) => new Date(monday + hours * 3_600_000);
  sent.length = 0;
  assert.equal(await insights.runWeeklySummary(at(-10)), 0, 'not on Sunday');
  assert.equal(await insights.runWeeklySummary(at(8)), 0, 'not before 09:00');
  assert.equal(await insights.runWeeklySummary(at(33.5)), 0, 'not on Tuesday');
  assert.equal(sent.length, 0);

  assert.equal(await insights.runWeeklySummary(at(9.5)), 1);
  assert.equal(sent.length, 1);
  assert.equal(sent[0].to, 'owner@bugs.test');
  assert.match(sent[0].subject, /^Bug tracker: week of \d/);
  for (const part of ['OLDEST OPEN BUGS', 'Dashboard: an old one', 'DEVELOPERS', 'Dev Kumar', 'Average time to fix', '/bugs#dashboard']) assert.ok(sent[0].text.includes(part), part);
  assert.match(sent[0].text, /last week \d+ bugs were reported and \d+ closed/);
  // The hourly job runs again: nobody gets it twice.
  assert.equal(await insights.runWeeklySummary(at(10.5)), 0);
  assert.equal(sent.length, 1);

  // Switched off: next Monday brings nothing.
  await notes.setPrefs(admin, ['WEEKLY']);
  assert.equal(await insights.runWeeklySummary(at(7 * 24 + 9.5)), 0);
  await notes.setPrefs(admin, []);
  assert.equal(await insights.runWeeklySummary(at(7 * 24 + 9.5)), 1);
  assert.equal(await raw.bugSummaryLog.count({ where: { status: 'DRY_RUN' } }), 2);

  // The whole hourly job runs clean.
  await bugTick(at(12));
});

// ── BT5: releases and the board ─────────────────────────────────────────────

let web144 = '';
let android = '';

test('bugs releases: developers and the super admin add and edit; one name per app; testers read', async () => {
  const make = (over: Record<string, unknown>) => releases.createReleaseSchema.parse({ app: 'WEB_APP', name: 'Web 1.44', ...over });
  await assert.rejects(() => releases.createRelease(make({}), qa), /developer or the super admin/);
  const r = await releases.createRelease(make({ plannedFor: '2026-11-20', notes: 'Month-end billing fixes.' }), dev);
  web144 = r.id;
  assert.equal(r.label, 'Web app Web 1.44');
  assert.equal(r.plannedFor, '2026-11-20');
  assert.equal(r.deployed, false);
  assert.deepEqual(r.counts, { fixed: 0, waiting: 0, verified: 0, sentBack: 0, found: 0 });
  // One name per app, whatever the capitals; the same name in another app is fine.
  await assert.rejects(() => releases.createRelease(make({ name: 'WEB 1.44' }), admin), ConflictError);
  android = (await releases.createRelease(make({ app: 'ANDROID_APP', name: 'Web 1.44' }), admin)).id;
  await releases.updateRelease(android, releases.updateReleaseSchema.parse({ name: '1.4.2' }), dev);
  assert.throws(() => make({ name: '  ' }), /Give the release a name/);
  assert.throws(() => make({ plannedFor: '2026-02-30' }), /real date/);
  assert.throws(() => make({ app: 'DESKTOP' }), /Choose the app/);
  assert.throws(() => releases.updateReleaseSchema.parse({ app: 'API' }), /Unrecognized key/);
  await assert.rejects(() => releases.updateRelease(web144, releases.updateReleaseSchema.parse({ notes: 'x' }), qa), /developer or the super admin/);

  // What is coming is listed before what went out; the forms get every release that isn't archived.
  assert.deepEqual((await releases.listReleases()).map((x) => x.name).sort(), ['1.4.2', 'Web 1.44']);
  assert.deepEqual((await releases.listReleases({ app: 'ANDROID_APP' })).map((x) => x.name), ['1.4.2']);
  assert.equal((await releases.releaseChoices()).length, 2);
});

let relBug = 0;
let relBug2 = 0;

test('bugs releases: a fix names its release; QA sees it only once the release is deployed', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  // Found in a release from the list: its name fills the version.
  relBug = (await bugs.createBug(report({ title: 'Release: coupon count is off by one', moduleId: mess, actual: 'One coupon too many is counted.', foundInReleaseId: web144 }), qa)).number;
  relBug2 = (await bugs.createBug(report({ title: 'Release: menu photo is sideways', moduleId: mess, actual: 'The photo is rotated on the menu.', type: 'SUGGESTION' }), qa2)).number;
  const b = await bugs.getBug(relBug, qa);
  assert.equal(b.appVersion, 'Web 1.44');
  assert.equal(b.foundInRelease?.id, web144);
  // A release of another app, or one that doesn't exist, is refused.
  await assert.rejects(() => bugs.createBug(report({ title: 'Release: wrong app', moduleId: mess, foundInReleaseId: android }), qa), /Android app/);
  await assert.rejects(() => workflow.moveBug(relBug, moveSchema.parse({ action: 'fix', note: 'Counted from zero.', fixedInReleaseId: android }), dev), /Android app/);
  await assert.rejects(() => workflow.moveBug(relBug, moveSchema.parse({ action: 'fix', note: 'Counted from zero.', fixedInReleaseId: '00000000-0000-4000-8000-000000000000' }), dev), /from the list/);
  // Typing a version by hand takes the release off again.
  const typed = await bugs.updateBug(relBug, updateBugSchema.parse({ appVersion: 'web build 57' }), qa);
  assert.equal(typed.foundInRelease, null);
  assert.equal((await bugs.updateBug(relBug, updateBugSchema.parse({ foundInReleaseId: web144 }), qa)).appVersion, 'Web 1.44');

  await notes.settle();
  sent.length = 0;
  for (const n of [relBug, relBug2]) {
    const fixed = await workflow.moveBug(n, moveSchema.parse({ action: 'fix', note: 'Fixed in the mess module.', fixedInReleaseId: web144, fixedIn: 'ignored when a release is chosen' }), dev);
    assert.equal(fixed.fixedIn, 'Web 1.44');
    assert.deepEqual({ id: fixed.fixedInRelease?.id, deployed: fixed.fixedInRelease?.deployed }, { id: web144, deployed: false });
  }
  await notes.settle();
  assert.ok(sent.length > 0 && sent.every((m) => /\] Fixed · /.test(m.subject)));

  // Not deployed: the tester's "ready to verify" leaves them out; they wait in their own list.
  const work = async (who: BugActor, key: string) => (await workflow.myWork(who)).groups.find((g) => g.key === key)!;
  const numbersOf = async (filters: Record<string, string>) => (await bugs.listBugs(listBugsSchema.parse({ ...filters, limit: '100' }))).items.map((i) => i.number);
  assert.ok(!(await numbersOf((await work(qa, 'to-verify')).filters)).includes(relBug));
  const waiting = await work(qa, 'not-deployed');
  assert.equal(waiting.attention, false);
  assert.deepEqual((await numbersOf(waiting.filters)).sort(), [relBug, relBug2].sort());
  assert.equal(waiting.count, 2);
  assert.deepEqual((await numbersOf({ fixedInReleaseId: web144 })).sort(), [relBug, relBug2].sort());
  assert.deepEqual(await numbersOf({ foundInReleaseId: web144 }), [relBug]);
  const before = await releases.getRelease(web144);
  assert.deepEqual(before.counts, { fixed: 2, waiting: 2, verified: 0, sentBack: 0, found: 1 });
  assert.match(before.releaseNotes, /^## Web app Web 1\.44\nPlanned for 20 Nov 2026\n\nMonth-end billing fixes\.\n\n### Fixed\n- Release: coupon count is off by one \(BUG-\d+\)\n\n### Improved\n- Release: menu photo is sideways \(BUG-\d+\)$/);
});

test('bugs releases: marking it deployed tells QA what is ready, once, in one email each', async () => {
  await notes.settle();
  sent.length = 0;
  await assert.rejects(() => releases.setDeployed(web144, true, qa), /developer or the super admin/);
  const r = await releases.setDeployed(web144, true, dev);
  await notes.settle();
  assert.equal(r.deployed, true);
  assert.equal(r.deployedBy?.name, 'Dev Kumar');
  // Every tester, and whoever follows the bugs, but not the one who deployed it.
  const to = sent.map((m) => m.to).sort();
  assert.ok(to.includes('asha@bugs.test') && to.includes('bina@bugs.test') && !to.includes('devk@bugs.test'));
  assert.equal(new Set(to).size, to.length, 'one email each');
  const asha = sent.find((m) => m.to === 'asha@bugs.test')!;
  assert.equal(asha.subject, 'Web app Web 1.44 is deployed: 2 fixes are ready to verify');
  assert.ok(asha.text.includes(`BUG-${relBug}`) && asha.text.includes(`BUG-${relBug2}`));
  assert.deepEqual((await mine(qa)).slice(-2).map((n) => [n.kind, n.snippet]), [['DEPLOYED', 'Web app Web 1.44'], ['DEPLOYED', 'Web app Web 1.44']]);
  const bell = await notes.listNotifications(qa, { page: 1, limit: 5, unread: true });
  assert.match(bell.items[0].text, /^Dev Kumar deployed the fix for BUG-\d+$/);

  // The bugs' threads say so, and the tester's list now has them.
  const b = await bugs.getBug(relBug, qa);
  assert.deepEqual(b.events.at(-1)!.changes, { release: 'Web app Web 1.44' });
  assert.equal(b.events.at(-1)!.type, 'DEPLOYED');
  assert.equal(b.fixedInRelease?.deployed, true);
  const ready = (await workflow.myWork(qa)).groups.find((g) => g.key === 'to-verify')!;
  assert.ok((await bugs.listBugs(listBugsSchema.parse({ ...ready.filters, limit: '100' }))).items.some((i) => i.number === relBug));
  assert.equal((await workflow.myWork(qa)).groups.find((g) => g.key === 'not-deployed')!.count, 0);

  // Marking it again changes nothing and tells nobody.
  sent.length = 0;
  await releases.setDeployed(web144, true, admin);
  await notes.settle();
  assert.equal(sent.length, 0);

  // QA verifies one and sends the other back: the release's numbers and notes follow.
  await workflow.moveBug(relBug, moveSchema.parse({ action: 'close' }), qa);
  await workflow.moveBug(relBug2, moveSchema.parse({ action: 'reopen', note: 'Still sideways on iPhone.' }), qa);
  const after = await releases.getRelease(web144);
  assert.deepEqual(after.counts, { fixed: 2, waiting: 0, verified: 1, sentBack: 1, found: 1 });
  assert.ok(after.releaseNotes.includes('coupon count') && !after.releaseNotes.includes('menu photo'), 'a fix sent back is left out of the notes');
  assert.match(after.releaseNotes, /\nReleased \d+ \w+ \d{4}\n/);

  // A mistake can be taken back; nobody is told. (The emails about QA's two moves above have gone first.)
  await notes.settle();
  sent.length = 0;
  assert.equal((await releases.setDeployed(web144, false, dev)).deployed, false);
  await notes.settle();
  assert.equal(sent.length, 0);
  await releases.setDeployed(web144, true, dev);
});

test('bugs releases: renaming keeps the bugs in step; only the super admin archives', async () => {
  const renamed = await releases.updateRelease(web144, releases.updateReleaseSchema.parse({ name: '18 Nov', plannedFor: null }), admin);
  assert.equal(renamed.label, 'Web app 18 Nov');
  assert.equal(renamed.plannedFor, null);
  const b = await bugs.getBug(relBug, qa);
  assert.equal(b.fixedIn, '18 Nov');
  assert.equal(b.appVersion, '18 Nov');

  await assert.rejects(() => releases.setArchived(web144, true, dev), /Only the super admin/);
  assert.equal((await releases.setArchived(web144, true, admin)).archived, true);
  assert.ok(!(await releases.releaseChoices()).some((x) => x.id === web144), 'gone from the choices');
  assert.ok(!(await releases.listReleases()).some((x) => x.id === web144));
  assert.ok((await releases.listReleases({ includeArchived: true })).some((x) => x.id === web144));
  assert.equal((await bugs.getBug(relBug, qa)).fixedInRelease?.id, web144, 'the bugs that name it keep it');
  await assert.rejects(() => workflow.moveBug(relBug2, moveSchema.parse({ action: 'fix', note: 'Rotated by its EXIF tag.', fixedInReleaseId: web144 }), dev), /archived/);
  await assert.rejects(() => releases.createRelease(releases.createReleaseSchema.parse({ app: 'WEB_APP', name: '18 nov' }), dev), /Restore it instead/);
  await assert.rejects(() => releases.setDeployed(web144, false, dev), /archived/);
  await assert.rejects(() => releases.getRelease('00000000-0000-4000-8000-000000000000'), NotFoundError);
  assert.equal((await releases.setArchived(web144, false, admin)).archived, false);
});

test('bugs board: every status is a column; each card carries the moves this person may make', async () => {
  const everything = listBugsSchema.parse({});
  const d = await workflow.board(everything, dev);
  assert.deepEqual(d.columns.map((c) => c.status), ['OPEN', 'REOPENED', 'IN_PROGRESS', 'NEEDS_INFO', 'FIXED', 'CLOSED']);
  for (const c of d.columns) {
    assert.ok(c.cards.length <= 40 && c.cards.every((card) => card.status === c.status));
    if (c.status !== 'CLOSED') assert.equal(c.total, await raw.bug.count({ where: { status: c.status } }), c.status);
  }
  // The same rule as on a bug's page.
  const open = d.columns[0].cards[0];
  assert.deepEqual(open.actions, ['start', 'ask', 'fix', 'suggest']);
  assert.deepEqual((await bugs.getBug(open.number, dev)).can.actions, open.actions);
  const q = await workflow.board(everything, qa);
  assert.deepEqual(q.columns[0].cards.find((c) => c.number === open.number)!.actions, ['close']);
  const fixedCard = q.columns.find((c) => c.status === 'FIXED')!.cards[0];
  assert.deepEqual(fixedCard.actions, ['close', 'reopen']);
  assert.deepEqual(d.columns.find((c) => c.status === 'CLOSED')!.cards[0].actions, [], 'a developer can do nothing to a closed bug');
  assert.deepEqual(q.columns.find((c) => c.status === 'CLOSED')!.cards[0].actions, ['reopen']);
  // Most severe first within a column.
  const order = ['CRITICAL', 'MAJOR', 'MINOR', 'TRIVIAL'];
  const sev = d.columns[0].cards.map((c) => order.indexOf(c.severity));
  assert.deepEqual(sev, [...sev].sort((a, b) => a - b));

  // The list's filters narrow the board; a status filter is ignored (the columns are the statuses).
  const minePlusStatus = await workflow.board(listBugsSchema.parse({ assigneeId: dev.id, status: 'OPEN' }), dev);
  assert.ok(minePlusStatus.columns.every((c) => c.cards.every((card) => card.assignee?.id === dev.id)));
  assert.ok(minePlusStatus.columns.some((c) => c.status !== 'OPEN' && c.total > 0));
  // Closed shows what was closed lately only.
  const old = await raw.bug.findFirstOrThrow({ where: { status: 'CLOSED' } });
  const closedBefore = d.columns.find((c) => c.status === 'CLOSED')!.total;
  await raw.bug.update({ where: { id: old.id }, data: { closedAt: new Date(Date.now() - 20 * 86_400_000) } });
  assert.equal((await workflow.board(everything, dev)).columns.find((c) => c.status === 'CLOSED')!.total, closedBefore - 1);
});

// ── BT6: test checklists and runs ───────────────────────────────────────────

let smoke = '';
let smokeItems: string[] = [];

test('bugs checklists: QA and the super admin write them; items keep their order; one name each', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const make = (over: Record<string, unknown> = {}) =>
    testing.createChecklistSchema.parse({
      name: 'Smoke test',
      description: 'The ten-minute pass before a release.',
      app: 'WEB_APP',
      items: [{ title: 'Sign in with a code' }, { title: 'Add a resident', detail: '1. Residents → Add\n2. Save\n\nThe resident appears in the list.' }, { title: 'Mess menu shows today', moduleId: mess }],
      ...over,
    });
  await assert.rejects(() => testing.createChecklist(make(), dev), /Only QA or the super admin/);
  const c = await testing.createChecklist(make(), qa);
  smoke = c.id;
  smokeItems = c.items.map((i) => i.id);
  assert.deepEqual(c.items.map((i) => i.title), ['Sign in with a code', 'Add a resident', 'Mess menu shows today']);
  assert.equal(c.items[2].module?.name, 'Mess');
  assert.equal(c.app, 'WEB_APP');
  await assert.rejects(() => testing.createChecklist(make({ name: 'SMOKE TEST' }), admin), ConflictError);
  await assert.rejects(() => testing.createChecklist(make({ name: 'Other', items: [{ title: 'x1', moduleId: '00000000-0000-4000-8000-000000000000' }] }), qa), /module from the list/);
  assert.throws(() => make({ name: 'S' }), /at least 2/);
  assert.throws(() => make({ items: [{ title: 'x' }] }), /Each item must be at least 2/);
  assert.throws(() => make({ items: Array.from({ length: 201 }, (_, i) => ({ title: `Item ${i}` })) }), /at most 200/);

  // An edit sends the whole list: kept items keep their id, the order is the list's, the rest go.
  const edited = await testing.updateChecklist(
    smoke,
    testing.updateChecklistSchema.parse({ items: [{ id: smokeItems[2], title: 'Mess menu shows today', moduleId: mess }, { id: smokeItems[0], title: 'Sign in with an emailed code' }, { title: 'Record a payment' }] }),
    admin,
  );
  assert.deepEqual(edited.items.map((i) => i.title), ['Mess menu shows today', 'Sign in with an emailed code', 'Record a payment']);
  assert.deepEqual([edited.items[0].id, edited.items[1].id], [smokeItems[2], smokeItems[0]]);
  assert.ok(!edited.items.some((i) => i.id === smokeItems[1]), 'the item left out is removed');
  // An id from another checklist is not adopted: it becomes a new item here.
  const other = await testing.createChecklist(make({ name: 'Billing pass', app: null, items: [{ title: 'Raise an invoice' }] }), qa);
  const adopted = await testing.updateChecklist(smoke, testing.updateChecklistSchema.parse({ items: [...edited.items.map((i) => ({ id: i.id, title: i.title, moduleId: i.module?.id ?? null })), { id: other.items[0].id, title: 'Stolen item' }] }), qa);
  assert.ok(!adopted.items.some((i) => i.id === other.items[0].id));
  assert.equal((await testing.getChecklist(other.id)).items.length, 1);
  smokeItems = adopted.items.map((i) => i.id);
  await assert.rejects(() => testing.updateChecklist(smoke, testing.updateChecklistSchema.parse({ name: 'x2' }), dev), /Only QA or the super admin/);

  // Archived: gone from the list, and can't be run.
  await testing.updateChecklist(other.id, testing.updateChecklistSchema.parse({ archived: true }), admin);
  assert.deepEqual((await testing.listChecklists()).map((x) => x.name), ['Smoke test']);
  assert.equal((await testing.listChecklists({ includeArchived: true })).length, 2);
  await assert.rejects(() => testing.startRun(testing.startRunSchema.parse({ checklistId: other.id, app: 'API' }), qa), /archived/);
});

let run1 = '';

test('bugs runs: a run copies the checklist; each item is pass, fail or skipped; a failure names its bug', async () => {
  const start = (over: Record<string, unknown>) => testing.startRunSchema.parse({ checklistId: smoke, ...over });
  // Against a release: the app is the release's. A checklist for the web app can't be run against an Android release.
  await assert.rejects(() => testing.startRun(start({ releaseId: android }), qa), /another app/);
  await assert.rejects(() => testing.startRun(start({ releaseId: '00000000-0000-4000-8000-000000000000' }), qa), /from the list/);
  const empty = await testing.createChecklist(testing.createChecklistSchema.parse({ name: 'Nothing yet' }), qa);
  await assert.rejects(() => testing.startRun(testing.startRunSchema.parse({ checklistId: empty.id, app: 'API' }), qa), /nothing on it/);
  await assert.rejects(() => testing.startRun(testing.startRunSchema.parse({ checklistId: empty.id }), qa), /nothing on it|app/);

  // Anyone on the tracker can run one.
  const r = await testing.startRun(start({ releaseId: web144 }), dev);
  run1 = r.id;
  assert.equal(r.app, 'WEB_APP');
  assert.equal(r.release?.id, web144);
  assert.equal(r.environment, 'STAGING');
  assert.equal(r.checklist.name, 'Smoke test');
  assert.deepEqual(r.counts, { total: 4, pass: 0, fail: 0, skipped: 0, untested: 4 });
  assert.deepEqual(r.results.map((x) => x.title), ['Mess menu shows today', 'Sign in with an emailed code', 'Record a payment', 'Stolen item']);
  assert.equal(r.results[0].module?.name, 'Mess');

  // The checklist changes afterwards; the run does not.
  await testing.updateChecklist(smoke, testing.updateChecklistSchema.parse({ name: 'Smoke test v2', items: [{ id: smokeItems[0], title: 'Mess menu shows the right day' }] }), qa);
  const same = await testing.getRun(run1, qa);
  assert.equal(same.results.length, 4);
  assert.equal(same.results[0].title, 'Mess menu shows today');
  assert.equal(same.checklist.name, 'Smoke test');

  const [a, b, c, d] = same.results.map((x) => x.id);
  const mark = (id: string, body: Record<string, unknown>, who: BugActor = qa) => testing.recordResult(run1, id, testing.resultSchema.parse(body), who);
  await mark(a, { outcome: 'PASS' });
  await mark(b, { outcome: 'SKIPPED', note: 'No mail on staging today.' });
  // A failure, linked to a bug that already exists.
  const failed = await mark(c, { outcome: 'FAIL', note: 'The receipt is blank.', bug: `BUG-${relBug}` }, dev);
  const row = failed.results.find((x) => x.id === c)!;
  assert.deepEqual({ outcome: row.outcome, bug: row.bug?.number, by: row.testedBy?.name }, { outcome: 'FAIL', bug: relBug, by: 'Dev Kumar' });
  assert.deepEqual(failed.counts, { total: 4, pass: 1, fail: 1, skipped: 1, untested: 1 });
  await assert.rejects(() => mark(d, { outcome: 'FAIL', bug: 'BUG-999999' }), NotFoundError);
  await assert.rejects(() => mark(d, { outcome: 'FAIL', bug: 'twelve' }), /bug number/);
  assert.throws(() => testing.resultSchema.parse({ outcome: 'MAYBE' }));
  await assert.rejects(() => testing.recordResult(run1, '00000000-0000-4000-8000-000000000000', testing.resultSchema.parse({ outcome: 'PASS' }), qa), /not on this run/);
  // Only a failure has a bug: passing it takes the link off. Null puts it back to "not tested".
  assert.equal((await mark(c, { outcome: 'PASS' })).results.find((x) => x.id === c)!.bug, null);
  const cleared = (await mark(c, { outcome: null })).results.find((x) => x.id === c)!;
  assert.deepEqual({ outcome: cleared.outcome, note: cleared.note, by: cleared.testedBy }, { outcome: null, note: null, by: null });

  // Reporting a bug from an item: the new bug is that item's failure.
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const reported = await bugs.createBug(report({ title: 'Runs: payment receipt is blank', moduleId: mess, actual: 'The receipt opens with no rows.', testResultId: c, foundInReleaseId: web144 }), qa);
  const after = await testing.getRun(run1, qa);
  assert.deepEqual({ outcome: after.results.find((x) => x.id === c)!.outcome, bug: after.results.find((x) => x.id === c)!.bug?.number }, { outcome: 'FAIL', bug: reported.number });
  assert.deepEqual(reported.foundByTests, [{ runId: run1, checklist: 'Smoke test', item: 'Record a payment' }]);
  assert.deepEqual((reported.events[0].changes as Record<string, unknown>).test, { run: 'Smoke test', item: 'Record a payment' });
  await assert.rejects(() => bugs.createBug(report({ title: 'Runs: no such item', moduleId: mess, testResultId: '00000000-0000-4000-8000-000000000000' }), qa), /test item was not found/);

  // Finished: closed to changes until reopened. Whoever started it, or the super admin, may delete it.
  const done = await testing.finishRun(run1, true, qa);
  assert.equal(done.finished, true);
  assert.equal(done.finishedBy?.name, 'Asha QA');
  assert.equal(done.can.record, false);
  await assert.rejects(() => mark(d, { outcome: 'PASS' }), /finished/);
  await assert.rejects(() => bugs.createBug(report({ title: 'Runs: after the end', moduleId: mess, testResultId: d }), qa), /finished/);
  assert.equal((await testing.finishRun(run1, false, dev)).finished, false);
  await mark(d, { outcome: 'PASS' });
  await testing.finishRun(run1, true, qa);

  // The lists: by checklist, by release, open or finished; a checklist shows how its last run went.
  const run2 = await testing.startRun(testing.startRunSchema.parse({ checklistId: smoke, environment: 'PRODUCTION' }), qa);
  assert.equal(run2.release, null);
  assert.equal(run2.results.length, 1, 'the checklist as it is now');
  const list = (f: Record<string, unknown>) => testing.listRuns(testing.listRunsSchema.parse(f));
  assert.deepEqual((await list({ checklistId: smoke })).items.map((x) => x.id), [run2.id, run1]);
  assert.deepEqual((await list({ releaseId: web144 })).items.map((x) => x.id), [run1]);
  assert.deepEqual((await list({ state: 'open' })).items.map((x) => x.id), [run2.id]);
  assert.deepEqual((await list({ state: 'finished' })).items[0].counts, { total: 4, pass: 2, fail: 1, skipped: 1, untested: 0 });
  const listed = (await testing.listChecklists()).find((x) => x.id === smoke)!;
  assert.deepEqual({ runs: listed.runCount, last: listed.lastRun?.id, items: listed.itemCount }, { runs: 2, last: run2.id, items: 1 });
  assert.equal((await testing.getRun(run2.id, dev)).can.delete, false);
  await assert.rejects(() => testing.deleteRun(run2.id, dev), /whoever started/);
  await testing.deleteRun(run2.id, qa);
  await assert.rejects(() => testing.getRun(run2.id, qa), NotFoundError);
  assert.equal((await bugs.getBug(reported.number, qa)).foundByTests.length, 1, 'a bug outlives nothing here: its run is still there');
});

// ── Test checklists to and from a sheet ─────────────────────────────────────

test('bugs checklists import: looked at first; mistakes stop it; then all at once', async () => {
  const before = await raw.bugChecklist.count();
  const row = (n: number, checklist: string, item: string, over: Record<string, string> = {}) => ({ row: n, checklist, item, app: '', description: '', detail: '', module: '', ...over });
  const rows = [
    row(2, 'Import: month end', 'Raise the month’s invoices', { app: 'web app', description: 'Last working day of the month.', module: 'billing AND payments' }),
    row(3, 'IMPORT: Month End', 'The late fee is charged once', { detail: '1. Open an overdue invoice\r\n2. Wait a day\n\n\n\nOne late fee.' }),
    row(4, '', '', {}),
    row(5, 'Import: mess', 'Menu shows today', { module: 'No such module' }),
    row(6, 'Smoke test v2', 'Should be skipped: the name exists'),
  ];
  const parse = (over: Record<string, unknown>) => checklistIo.importSchema.parse({ rows, ...over });

  // A tester or the super admin imports; a developer can't.
  await assert.rejects(() => checklistIo.importChecklists(parse({}), dev), /Only QA or the super admin/);
  const look = await checklistIo.importChecklists(parse({}), qa);
  assert.equal(look.dryRun, true);
  assert.deepEqual(look.checklists.map((c) => [c.name, c.action, c.items, c.app]), [
    ['Import: month end', 'create', 2, 'WEB_APP'],
    ['Import: mess', 'create', 1, null],
    ['Smoke test v2', 'skip', 1, null],
  ]);
  assert.deepEqual(look.totals, { created: 2, replaced: 0, skipped: 1, items: 3 });
  assert.deepEqual(look.errors, []);
  assert.deepEqual(look.warnings.map((w) => w.row), [5], 'an unknown module is a warning, not an error');
  assert.equal(await raw.bugChecklist.count(), before, 'nothing is written while looking');

  // One bad row stops the whole file.
  const bad = await checklistIo.importChecklists(checklistIo.importSchema.parse({ rows: [...rows, row(7, 'Import: mess', 'x'), row(8, 'X', 'Too short a checklist'), row(9, 'Import: mess', 'Fine', { app: 'Desktop' }), row(10, 'Import: mess', '', { detail: 'Steps with no item' })], dryRun: false }), qa);
  assert.equal(bad.dryRun, true);
  assert.deepEqual(bad.errors.map((e) => e.row), [7, 8, 9, 10]);
  assert.match(bad.errors[2].message, /not one of the apps/);
  assert.equal(await raw.bugChecklist.count(), before);

  // Sent for real: both new checklists, in order, the module found by name, the steps tidied.
  const done = await checklistIo.importChecklists(parse({ dryRun: false }), qa);
  assert.equal(done.dryRun, false);
  assert.equal(await raw.bugChecklist.count(), before + 2);
  const month = (await testing.listChecklists()).find((c) => c.name === 'Import: month end')!;
  const full = await testing.getChecklist(month.id);
  assert.deepEqual(full.items.map((i) => i.title), ['Raise the month’s invoices', 'The late fee is charged once']);
  assert.equal(full.items[0].module?.name, 'Billing and payments');
  assert.equal(full.items[1].detail, '1. Open an overdue invoice\n2. Wait a day\n\nOne late fee.');
  assert.deepEqual([full.app, full.description], ['WEB_APP', 'Last working day of the month.']);

  // Again with "replace": the existing checklist gets the file's items; runs keep theirs.
  const run = await testing.startRun(testing.startRunSchema.parse({ checklistId: month.id }), qa);
  const again = await checklistIo.importChecklists(checklistIo.importSchema.parse({ rows: [row(2, 'import: MONTH END', 'Only this one now')], existing: 'replace', dryRun: false }), admin);
  assert.deepEqual(again.checklists.map((c) => [c.name, c.action, c.items, c.existingItems]), [['Import: month end', 'replace', 1, 2]]);
  assert.deepEqual((await testing.getChecklist(month.id)).items.map((i) => i.title), ['Only this one now']);
  assert.equal((await testing.getRun(run.id, qa)).results.length, 2, 'a run keeps the items it began with');
  assert.equal((await testing.getChecklist(month.id)).description, 'Last working day of the month.', 'a blank description leaves the old one');

  // The limits.
  assert.throws(() => checklistIo.importSchema.parse({ rows: [] }), /no rows/);
  const big = Array.from({ length: 201 }, (_, i) => row(i + 2, 'Import: too big', `Item number ${i + 1}`));
  assert.match((await checklistIo.importChecklists(checklistIo.importSchema.parse({ rows: big }), qa)).errors[0].message, /at most 200/);
});

test('bugs checklists export: the same columns the import reads, so a file can go out and come back', async () => {
  const all = await checklistIo.exportChecklists({}, new Date('2026-11-17T06:00:00Z'));
  assert.equal(all.filename, 'hostelcare-test-cases-2026-11-17.xlsx');
  assert.equal(all.bytes.subarray(0, 2).toString(), 'PK');
  const live = await raw.bugChecklist.findMany({ where: { archivedAt: null }, include: { _count: { select: { items: true } } } });
  assert.equal(all.checklists, live.length);
  assert.equal(all.items, live.reduce((n, c) => n + Math.max(1, c._count.items), 0), 'one row per item; an empty checklist still has its row');
  const month = (await testing.listChecklists()).find((c) => c.name === 'Import: month end')!;
  const one = await checklistIo.exportChecklists({ ids: [month.id] }, new Date('2026-11-17T06:00:00Z'));
  assert.deepEqual([one.checklists, one.items, one.filename], [1, 1, 'hostelcare-test-cases-import-month-end-2026-11-17.xlsx']);
  assert.ok((await checklistIo.exportChecklists({ includeArchived: true })).checklists > all.checklists, 'archived ones only when asked');
  assert.equal(checklistIo.templateWorkbook().bytes.subarray(0, 2).toString(), 'PK');
  assert.deepEqual([...checklistIo.COLUMNS], ['Checklist', 'App', 'Description', 'Item', 'How to test it', 'Module']);
});

// ── BT6: GitHub ─────────────────────────────────────────────────────────────

test('bugs github: which bugs a commit message names, and whether it says it fixes them', () => {
  const refs = (t: string) => github.bugRefs(t);
  assert.deepEqual(refs('Fixes BUG-12'), [{ number: 12, fixes: true }]);
  assert.deepEqual(refs('fix: bug-7 and BUG-8, closes BUG-9. See also BUG-10'), [{ number: 7, fixes: true }, { number: 8, fixes: true }, { number: 9, fixes: true }, { number: 10, fixes: false }]);
  assert.deepEqual(refs('Resolved BUG-3: total was doubled'), [{ number: 3, fixes: true }]);
  assert.deepEqual(refs('Work on BUG-5 (not done)'), [{ number: 5, fixes: false }]);
  assert.deepEqual(refs('prefix-BUG-5x and DEBUG-6 and BUG-'), [], 'only whole references');
  assert.deepEqual(refs('fixes the build'), []);
  assert.equal(refs(Array.from({ length: 40 }, (_, i) => `BUG-${i + 1}`).join(' ')).length, 20, 'no more than twenty from one message');
});

const REPO = 'rajkumariparihar/hostelcare-backend';
const sha = (n: number) => n.toString(16).padStart(40, '0');
let delivery = 0;
const deliver = (event: string, body: Record<string, unknown>, id = `test-delivery-${++delivery}`) => github.handleGithub(event, id, { repository: { full_name: REPO, default_branch: 'master' }, ...body });
const push = (branch: string, commits: { id: string; message: string; username?: string; email?: string }[]) =>
  deliver('push', { ref: `refs/heads/${branch}`, commits: commits.map((c) => ({ id: c.id, message: c.message, author: { name: 'Someone', username: c.username, email: c.email } })) });

let ghBug = 0;

test('bugs github: a commit that names a bug is linked; "Fixes" moves it to Fixed once it is on a main branch', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  ghBug = (await bugs.createBug(report({ title: 'GitHub: token count resets at midnight', moduleId: mess, actual: 'Tokens read zero after midnight.' }), qa)).number;
  // The developer tells the tracker who they are on GitHub; one member per username.
  assert.equal((await notes.setGithubLogin(dev, 'DevKumar-Hub')).githubLogin, 'devkumar-hub');
  await assert.rejects(() => notes.setGithubLogin(qa2, 'devkumar-hub'), /Another member/);
  // Exactly one release of the web app is coming: a fix from GitHub goes into it.
  const coming = await releases.createRelease(releases.createReleaseSchema.parse({ app: 'WEB_APP', name: 'Next web' }), dev);
  await notes.settle();
  sent.length = 0;

  // On a feature branch: linked, and nothing else.
  const first = await push('enterprise', [{ id: sha(1), message: `Fixes BUG-${ghBug}: keep the day's count\n\nLonger text.`, username: 'devkumar-hub' }]);
  assert.deepEqual(first, { ok: true, result: 'handled', linked: 1, fixed: 0 });
  let b = await bugs.getBug(ghBug, qa);
  assert.equal(b.status, 'OPEN');
  assert.deepEqual(b.code.map((c) => ({ kind: c.kind, ref: c.ref, url: c.url, title: c.title, state: c.state, fixes: c.fixes, branch: c.branch })), [
    { kind: 'COMMIT', ref: '0000000', url: `https://github.com/${REPO}/commit/${sha(1)}`, title: `Fixes BUG-${ghBug}: keep the day's count`, state: 'PUSHED', fixes: true, branch: 'enterprise' },
  ]);
  assert.equal(b.events.at(-1)!.type, 'CODE_LINKED');
  assert.equal(b.events.at(-1)!.actor?.name, 'Dev Kumar', 'credited to the developer whose GitHub username it is');

  // The same delivery again is ignored; the same commit reaching master moves the bug.
  assert.equal((await deliver('push', { ref: 'refs/heads/enterprise', commits: [] }, `test-delivery-${delivery}`)).result, 'duplicate');
  const merged = await push('master', [{ id: sha(1), message: `Fixes BUG-${ghBug}: keep the day's count`, username: 'devkumar-hub' }]);
  assert.deepEqual(merged, { ok: true, result: 'handled', linked: 0, fixed: 1 });
  await notes.settle();
  b = await bugs.getBug(ghBug, qa);
  assert.equal(b.status, 'FIXED');
  assert.equal(b.assignee?.name, 'Dev Kumar', 'the developer who fixed an unassigned bug owns the fix');
  assert.equal(b.fixLink, `https://github.com/${REPO}/commit/${sha(1)}`);
  assert.match(b.fixNote ?? '', /^Fixed by commit 0000000 in rajkumariparihar\/hostelcare-backend: Fixes BUG-\d+: keep the day's count$/);
  assert.equal(b.fixedInRelease?.id, coming.id);
  assert.equal(b.code[0].state, 'MERGED');
  assert.equal(b.code.length, 1, 'one link for one commit, whatever branches it is seen on');
  assert.ok(sent.some((m) => m.to === 'asha@bugs.test' && /\] Fixed · GitHub: token count/.test(m.subject)), 'the reporter is told, as for any fix');

  // QA reopens it. The old commit arriving again (another branch, a redelivery) does not "fix" it again.
  await workflow.moveBug(ghBug, moveSchema.parse({ action: 'reopen', note: 'Still zero at 00:01.' }), qa);
  assert.deepEqual(await push('deploy', [{ id: sha(1), message: `Fixes BUG-${ghBug}: keep the day's count`, username: 'devkumar-hub' }]), { ok: true, result: 'handled', linked: 0, fixed: 0 });
  assert.equal((await bugs.getBug(ghBug, qa)).status, 'REOPENED');
  // A new commit does. Nobody on the team matches its author: it is GitHub's.
  const again = await push('master', [{ id: sha(2), message: `Second try. Closes BUG-${ghBug}`, username: 'someone-else', email: 'stranger@example.com' }]);
  assert.deepEqual(again, { ok: true, result: 'handled', linked: 1, fixed: 1 });
  await notes.settle();
  b = await bugs.getBug(ghBug, qa);
  assert.equal(b.status, 'FIXED');
  const fixedEvent = b.events.filter((e) => e.type === 'STATUS').at(-1)!;
  assert.deepEqual({ id: fixedEvent.actor?.id, name: fixedEvent.actor?.name }, { id: 'github', name: 'GitHub' });
  assert.ok(!b.watchers.some((w) => w!.id === 'github'), 'GitHub follows nothing');
  assert.equal((await notes.listNotifications(qa, { page: 1, limit: 1, unread: false })).items[0].text, `GitHub marked BUG-${ghBug} as fixed`);
  // Matched by email when no username is known.
  await workflow.moveBug(ghBug, moveSchema.parse({ action: 'reopen', note: 'And again.' }), qa);
  await push('main', [{ id: sha(3), message: `resolves BUG-${ghBug}`, email: 'DEVK@bugs.test' }]);
  assert.equal((await bugs.getBug(ghBug, qa)).events.filter((e) => e.type === 'STATUS').at(-1)!.actor?.name, 'Dev Kumar');
});

test('bugs github: pull requests, mentions, and what is ignored', async () => {
  const mess = (await modules.listModules()).find((m) => m.name === 'Mess')!.id;
  const n = (await bugs.createBug(report({ title: 'GitHub: PR flow', moduleId: mess, actual: 'Needs a pull request.' }), qa)).number;
  const pr = (action: string, over: Record<string, unknown>) =>
    deliver('pull_request', { action, pull_request: { number: 41, title: 'Token counts', body: `Fixes BUG-${n}\n\nAlso touches BUG-${ghBug}.`, state: 'open', merged: false, user: { login: 'devkumar-hub' }, base: { ref: 'master' }, head: { ref: 'fix/tokens' }, ...over } });

  // Opened: linked to both bugs it names, nothing moved.
  assert.deepEqual(await pr('opened', {}), { ok: true, result: 'handled', linked: 2, fixed: 0 });
  let b = await bugs.getBug(n, qa);
  assert.equal(b.status, 'OPEN');
  assert.deepEqual(b.code.map((c) => [c.kind, c.ref, c.url, c.state, c.fixes]), [['PULL_REQUEST', '#41', `https://github.com/${REPO}/pull/41`, 'OPEN', true]]);
  // Closed without merging: still only a link.
  await pr('closed', { state: 'closed' });
  assert.deepEqual([(await bugs.getBug(n, qa)).status, (await bugs.getBug(n, qa)).code[0].state], ['OPEN', 'CLOSED']);
  // Merged into a feature branch: not yet. Merged into master: fixed. The bug it only mentions is not touched.
  await pr('closed', { state: 'closed', merged: true, base: { ref: 'enterprise' } });
  assert.equal((await bugs.getBug(n, qa)).status, 'OPEN');
  const before = (await bugs.getBug(ghBug, qa)).status;
  assert.deepEqual(await pr('closed', { state: 'closed', merged: true }), { ok: true, result: 'handled', linked: 0, fixed: 1 });
  b = await bugs.getBug(n, qa);
  assert.deepEqual([b.status, b.code[0].state, b.fixLink], ['FIXED', 'MERGED', `https://github.com/${REPO}/pull/41`]);
  const mentioned = await bugs.getBug(ghBug, qa);
  assert.equal(mentioned.status, before);
  assert.ok(mentioned.code.some((c) => c.ref === '#41' && !c.fixes));

  // A fix for a bug that is already closed is linked and nothing more; a bug that doesn't exist is nothing.
  await workflow.moveBug(n, moveSchema.parse({ action: 'close' }), qa);
  assert.deepEqual(await push('master', [{ id: sha(9), message: `Fixes BUG-${n} and BUG-987654` }]), { ok: true, result: 'handled', linked: 1, fixed: 0 });
  assert.equal((await bugs.getBug(n, qa)).status, 'CLOSED');

  // Not ours to read: a tag, a deleted branch, another kind of event, a payload with no repository, a repository off the list.
  assert.deepEqual(await deliver('push', { ref: 'refs/tags/v1', commits: [{ id: sha(10), message: `Fixes BUG-${ghBug}` }] }), { ok: true, result: 'handled', linked: 0, fixed: 0 });
  assert.equal((await deliver('issues', { action: 'opened' })).result, 'ignored');
  assert.equal((await github.handleGithub('ping', 'p1', { zen: 'Keep it simple.' })).result, 'pong');
  assert.equal((await github.handleGithub('push', 'p2', { ref: 'refs/heads/master', commits: [] })).result, 'ignored');
  assert.equal((await github.handleGithub('push', 'p3', { repository: { full_name: '../../etc/passwd x' }, commits: [] })).result, 'ignored');
  env.BUG_GITHUB_REPOS.push('rajkumariparihar/hostelcare-frontend');
  const off = await push('master', [{ id: sha(11), message: `Fixes BUG-${ghBug}` }]);
  env.BUG_GITHUB_REPOS.length = 0;
  assert.deepEqual([off.result, off.note], ['ignored', 'This repository is not on the list']);
  assert.ok(!(await bugs.getBug(ghBug, qa)).code.some((c) => c.url.endsWith(sha(11))));
  // A commit id that is not a hash never becomes a link.
  await push('master', [{ id: '"><script>alert(1)</script>', message: `Fixes BUG-${ghBug}` }]);
  assert.ok((await bugs.getBug(ghBug, qa)).code.every((c) => /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/(commit\/[0-9a-f]{40}|pull\/\d+)$/.test(c.url)));

  // The super admin's view; old deliveries are forgotten.
  const status = await github.githubStatus();
  assert.equal(status.configured, false, 'no secret in the test environment');
  assert.ok(status.recent.length > 0 && status.recent.length <= 10 && status.links >= 4);
  assert.equal(status.recent[0].repo, REPO);
  assert.equal(await github.purgeDeliveries(), 0);
  assert.ok((await github.purgeDeliveries(new Date(Date.now() + 31 * 86_400_000))) > 0);
  await notes.settle();
});

test('bugs: drop the throwaway schema', async () => {
  // Only ever the bug tracker test's own schema, by its exact name.
  await notes.settle();
  const schema = new URL(process.env.DATABASE_URL ?? '').searchParams.get('schema');
  if (schema === 'hc_bug_test') await raw.$executeRawUnsafe('DROP SCHEMA IF EXISTS hc_bug_test CASCADE');
  await raw.$disconnect();
});
