import { z } from 'zod';
import { BugApp, BugEnvironment, Role, type BugChecklist, type BugTestResult, type BugTestRun, type Prisma } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ConflictError, ForbiddenError, NotFoundError } from '../../lib/errors';
import type { BugActor } from './bug-access';
import { bugKey, bugNumberFrom } from './bug-rules';

/**
 * Test checklists and their runs (docs/bug-tracker-plan.md, BT6).
 *
 * A checklist is a reusable list of things to test. A run is one go through
 * it, usually against a release: each item is marked pass, fail or skipped. A
 * failure can be reported as a bug from there (the report form opens filled
 * in, and the new bug is linked to the item) or linked to a bug that already
 * exists.
 *
 * A run copies the checklist's items when it starts, so editing the checklist
 * later changes no past run. QA and the super admin write checklists; anyone
 * on the tracker can start a run and record results. A finished run is closed
 * to changes until it is reopened.
 */

export const TEST_LIMITS = { name: { min: 2, max: 80 }, description: 2_000, items: 200, title: { min: 2, max: 200 }, detail: 4_000, note: 2_000 } as const;
export const OUTCOMES = ['PASS', 'FAIL', 'SKIPPED'] as const;
export type Outcome = (typeof OUTCOMES)[number];

const clean = (v: string) => !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(v);
const line = (label: string, min: number, max: number) =>
  z
    .string()
    .trim()
    .min(min, `${label} must be at least ${min} characters`)
    .max(max, `${label} must be at most ${max} characters`)
    .refine((v) => clean(v) && !/[\r\n]/.test(v), `${label} must be a single line`);
const text = (label: string, max: number) =>
  z.union([z.string(), z.null()]).transform((v, ctx) => {
    const t = (v ?? '').replace(/\r\n?/g, '\n').trim();
    if (!t) return null;
    if (t.length > max) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} must be at most ${max.toLocaleString('en-IN')} characters` });
    if (!clean(t)) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `${label} contains invalid characters` });
    return t;
  });
const appOrNone = z.union([z.nativeEnum(BugApp), z.null()]);

const itemSchema = z
  .object({
    /** An item already on the checklist; without it, a new one. */
    id: z.string().uuid().optional(),
    title: line('Each item', TEST_LIMITS.title.min, TEST_LIMITS.title.max),
    detail: text('How to test it', TEST_LIMITS.detail).optional(),
    moduleId: z.union([z.string().uuid(), z.null()]).optional(),
  })
  .strict();

export const createChecklistSchema = z
  .object({
    name: line('Name', TEST_LIMITS.name.min, TEST_LIMITS.name.max),
    description: text('Description', TEST_LIMITS.description).optional(),
    app: appOrNone.optional(),
    items: z.array(itemSchema).max(TEST_LIMITS.items, `A checklist can have at most ${TEST_LIMITS.items} items`).default([]),
  })
  .strict();
export const updateChecklistSchema = z
  .object({
    name: line('Name', TEST_LIMITS.name.min, TEST_LIMITS.name.max),
    description: text('Description', TEST_LIMITS.description),
    app: appOrNone,
    archived: z.boolean(),
    /** The whole list, in order: items left out are removed. */
    items: z.array(itemSchema).max(TEST_LIMITS.items, `A checklist can have at most ${TEST_LIMITS.items} items`),
  })
  .partial()
  .strict()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

export const startRunSchema = z
  .object({
    checklistId: z.string().uuid('Choose a checklist'),
    releaseId: z.union([z.string().uuid('Choose a release'), z.null()]).optional(),
    /** Needed when no release is chosen and the checklist is for any app. */
    app: z.nativeEnum(BugApp).optional(),
    environment: z.nativeEnum(BugEnvironment).default(BugEnvironment.STAGING),
  })
  .strict();

export const resultSchema = z
  .object({
    /** Null puts the item back to "not tested". */
    outcome: z.union([z.enum(OUTCOMES), z.null()]),
    note: text('Note', TEST_LIMITS.note).optional(),
    /** A failure's bug that already exists, by its number; null takes the link off. */
    bug: z.union([z.number().int().positive(), z.string().trim().max(20), z.null()]).optional(),
  })
  .strict();

export const listRunsSchema = z.object({
  page: z.coerce.number().int().min(1).default(1),
  limit: z.coerce.number().int().min(1).max(100).default(20),
  checklistId: z.string().uuid().optional(),
  releaseId: z.string().uuid().optional(),
  state: z.enum(['open', 'finished']).optional(),
});

// ── Who ─────────────────────────────────────────────────────────────────────

function mayWriteChecklists(actor: BugActor) {
  if (actor.role !== Role.QA && actor.role !== Role.SUPER_ADMIN) throw new ForbiddenError('Only QA or the super admin can change checklists.');
}

async function names(ids: (string | null | undefined)[]) {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  const rows = unique.length ? await db.user.findMany({ where: { id: { in: unique } }, select: { id: true, name: true } }) : [];
  const map = new Map(rows.map((r) => [r.id, r.name]));
  return (id: string | null) => (id ? { id, name: map.get(id) ?? 'Unknown' } : null);
}

async function moduleNames(ids: (string | null | undefined)[]) {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  const rows = unique.length ? await db.bugModule.findMany({ where: { id: { in: unique } }, select: { id: true, name: true } }) : [];
  const map = new Map(rows.map((r) => [r.id, r.name]));
  return (id: string | null) => (id && map.has(id) ? { id, name: map.get(id)! } : null);
}

// ── Checklists ──────────────────────────────────────────────────────────────

async function loadChecklist(id: string) {
  const c = await db.bugChecklist.findUnique({ where: { id }, include: { items: { orderBy: { sortOrder: 'asc' } } } });
  if (!c) throw new NotFoundError('That checklist was not found.');
  return c;
}

async function assertFreeName(name: string, exceptId?: string) {
  const taken = await db.bugChecklist.findFirst({ where: { name: { equals: name, mode: 'insensitive' }, ...(exceptId ? { id: { not: exceptId } } : {}) }, select: { archivedAt: true } });
  if (taken) throw new ConflictError(taken.archivedAt ? 'A checklist with that name exists, archived. Restore it instead.' : 'A checklist with that name already exists.', 'CHECKLIST_EXISTS');
}

async function assertModules(ids: (string | null | undefined)[]) {
  const unique = [...new Set(ids.filter((v): v is string => !!v))];
  if (!unique.length) return;
  const found = await db.bugModule.count({ where: { id: { in: unique } } });
  if (found !== unique.length) throw new BadRequestError('Choose each item’s module from the list.', 'MODULE_NOT_FOUND');
}

const head = (c: BugChecklist) => ({ id: c.id, name: c.name, description: c.description, app: c.app, archived: !!c.archivedAt, createdAt: c.createdAt, updatedAt: c.updatedAt });

export async function listChecklists(f: { includeArchived?: boolean } = {}) {
  const rows = await db.bugChecklist.findMany({ where: f.includeArchived ? {} : { archivedAt: null }, orderBy: { name: 'asc' }, include: { _count: { select: { items: true, runs: true } } }, take: 500 });
  // Each checklist's latest run, to show when it was last gone through and how it went.
  const latest = await db.bugTestRun.findMany({ where: { checklistId: { in: rows.map((r) => r.id) } }, orderBy: { startedAt: 'desc' }, distinct: ['checklistId'], include: runParts });
  const last = new Map((await presentRuns(latest)).map((r) => [r.checklist.id, r]));
  return rows.map((c) => ({ ...head(c), itemCount: c._count.items, runCount: c._count.runs, lastRun: last.get(c.id) ?? null }));
}

export async function getChecklist(id: string) {
  const c = await loadChecklist(id);
  const [mod, runs, runCount] = await Promise.all([
    moduleNames(c.items.map((i) => i.moduleId)),
    db.bugTestRun.findMany({ where: { checklistId: id }, orderBy: { startedAt: 'desc' }, take: 10, include: runParts }),
    db.bugTestRun.count({ where: { checklistId: id } }),
  ]);
  return { ...head(c), itemCount: c.items.length, runCount, items: c.items.map((i) => ({ id: i.id, title: i.title, detail: i.detail, module: mod(i.moduleId) })), runs: await presentRuns(runs) };
}

type ItemInput = z.infer<typeof itemSchema>;

/** Replace a checklist's items with this list, in this order: kept ones keep their id. */
async function writeItems(tx: Prisma.TransactionClient, checklistId: string, items: ItemInput[], existing: { id: string }[]) {
  const mine = new Set(existing.map((e) => e.id));
  const keep = new Set(items.map((i) => i.id).filter((v): v is string => !!v && mine.has(v)));
  await tx.bugChecklistItem.deleteMany({ where: { checklistId, id: { notIn: [...keep] } } });
  for (const [sortOrder, i] of items.entries()) {
    const data = { title: i.title, detail: i.detail ?? null, moduleId: i.moduleId ?? null, sortOrder };
    if (i.id && keep.has(i.id)) await tx.bugChecklistItem.update({ where: { id: i.id }, data });
    else await tx.bugChecklistItem.create({ data: { ...data, checklistId } });
  }
}

export async function createChecklist(input: z.infer<typeof createChecklistSchema>, actor: BugActor) {
  mayWriteChecklists(actor);
  await assertFreeName(input.name);
  await assertModules(input.items.map((i) => i.moduleId));
  const id = await db.$transaction(async (tx) => {
    const c = await tx.bugChecklist.create({ data: { name: input.name, description: input.description ?? null, app: input.app ?? null, createdById: actor.id } });
    await writeItems(tx, c.id, input.items, []);
    return c.id;
  });
  return getChecklist(id);
}

export async function updateChecklist(id: string, input: z.infer<typeof updateChecklistSchema>, actor: BugActor) {
  mayWriteChecklists(actor);
  const c = await loadChecklist(id);
  if (input.name !== undefined && input.name !== c.name) await assertFreeName(input.name, id);
  if (input.items) await assertModules(input.items.map((i) => i.moduleId));
  const { items, archived, ...fields } = input;
  await db.$transaction(async (tx) => {
    await tx.bugChecklist.update({ where: { id }, data: { ...fields, ...(archived === undefined ? {} : { archivedAt: archived ? (c.archivedAt ?? new Date()) : null }) } });
    if (items) await writeItems(tx, id, items, c.items);
  });
  return getChecklist(id);
}

// ── Runs ────────────────────────────────────────────────────────────────────

const runParts = {
  release: { select: { id: true, name: true, deployedAt: true } },
  results: { select: { outcome: true } },
} satisfies Prisma.BugTestRunInclude;
type RunWithParts = BugTestRun & { release: { id: string; name: string; deployedAt: Date | null } | null; results: { outcome: string | null }[] };

function counts(results: { outcome: string | null }[]) {
  const n = (o: string | null) => results.filter((r) => r.outcome === o).length;
  return { total: results.length, pass: n('PASS'), fail: n('FAIL'), skipped: n('SKIPPED'), untested: n(null) };
}

async function presentRuns(rows: RunWithParts[]) {
  const who = await names(rows.flatMap((r) => [r.startedById, r.finishedById]));
  return rows.map((r) => ({
    id: r.id,
    checklist: { id: r.checklistId, name: r.checklistName },
    app: r.app,
    release: r.release ? { id: r.release.id, name: r.release.name, deployed: !!r.release.deployedAt, deployedAt: r.release.deployedAt } : null,
    environment: r.environment,
    startedBy: who(r.startedById),
    startedAt: r.startedAt,
    finished: !!r.finishedAt,
    finishedAt: r.finishedAt,
    finishedBy: who(r.finishedById),
    counts: counts(r.results),
  }));
}

export async function listRuns(f: z.infer<typeof listRunsSchema>) {
  const where: Prisma.BugTestRunWhereInput = {
    ...(f.checklistId ? { checklistId: f.checklistId } : {}),
    ...(f.releaseId ? { releaseId: f.releaseId } : {}),
    ...(f.state === 'open' ? { finishedAt: null } : f.state === 'finished' ? { finishedAt: { not: null } } : {}),
  };
  const [rows, total] = await Promise.all([db.bugTestRun.findMany({ where, orderBy: { startedAt: 'desc' }, skip: (f.page - 1) * f.limit, take: f.limit, include: runParts }), db.bugTestRun.count({ where })]);
  return { items: await presentRuns(rows), total, page: f.page, limit: f.limit, hasMore: (f.page - 1) * f.limit + rows.length < total };
}

async function loadRun(id: string) {
  const r = await db.bugTestRun.findUnique({ where: { id }, include: runParts });
  if (!r) throw new NotFoundError('That test run was not found.');
  return r;
}

const mayDelete = (run: BugTestRun, actor: BugActor) => actor.role === Role.SUPER_ADMIN || run.startedById === actor.id;

export async function getRun(id: string, actor: BugActor) {
  const r = await loadRun(id);
  const results = await db.bugTestResult.findMany({ where: { runId: id }, orderBy: { sortOrder: 'asc' }, include: { bug: { select: { number: true, title: true, status: true } } } });
  const [who, mod, [summary]] = await Promise.all([names(results.map((x) => x.testedById)), moduleNames(results.map((x) => x.moduleId)), presentRuns([r])]);
  return {
    ...summary,
    results: results.map((x) => ({
      id: x.id,
      title: x.title,
      detail: x.detail,
      module: mod(x.moduleId),
      outcome: x.outcome as Outcome | null,
      note: x.note,
      bug: x.bug ? { number: x.bug.number, key: bugKey(x.bug.number), title: x.bug.title, status: x.bug.status } : null,
      testedBy: who(x.testedById),
      testedAt: x.testedAt,
    })),
    can: { record: !r.finishedAt, finish: true, delete: mayDelete(r, actor) },
  };
}

/** Start a run: the checklist's items are copied in as they are now. */
export async function startRun(input: z.infer<typeof startRunSchema>, actor: BugActor) {
  const c = await loadChecklist(input.checklistId);
  if (c.archivedAt) throw new BadRequestError('That checklist is archived. Restore it to run it.', 'CHECKLIST_ARCHIVED');
  if (!c.items.length) throw new BadRequestError('That checklist has nothing on it yet. Add what to test first.', 'CHECKLIST_EMPTY');
  const release = input.releaseId ? await db.bugRelease.findUnique({ where: { id: input.releaseId } }) : null;
  if (input.releaseId && !release) throw new BadRequestError('Choose a release from the list.', 'RELEASE_NOT_FOUND');
  if (release?.archivedAt) throw new BadRequestError('That release is archived. Choose another.', 'RELEASE_ARCHIVED');
  const app = release?.app ?? input.app ?? c.app;
  if (!app) throw new BadRequestError('Choose the release, or the app, this run is testing.', 'APP_REQUIRED');
  if (c.app && c.app !== app) throw new BadRequestError('That checklist is for another app than this release.', 'CHECKLIST_WRONG_APP');
  const run = await db.bugTestRun.create({
    data: {
      checklistId: c.id,
      checklistName: c.name,
      app,
      releaseId: release?.id ?? null,
      environment: input.environment,
      startedById: actor.id,
      results: { create: c.items.map((i) => ({ itemId: i.id, title: i.title, detail: i.detail, moduleId: i.moduleId, sortOrder: i.sortOrder })) },
    },
  });
  return getRun(run.id, actor);
}

async function loadResult(runId: string, resultId: string): Promise<{ run: BugTestRun; result: BugTestResult }> {
  const result = await db.bugTestResult.findFirst({ where: { id: resultId, runId }, include: { run: true } });
  if (!result) throw new NotFoundError('That item is not on this run.');
  if (result.run.finishedAt) throw new ConflictError('This run is finished. Reopen it to change a result.', 'RUN_FINISHED');
  return { run: result.run, result };
}

/** Mark one item: pass, fail, skipped, or back to not tested. A failure can name its bug. */
export async function recordResult(runId: string, resultId: string, input: z.infer<typeof resultSchema>, actor: BugActor) {
  const { result } = await loadResult(runId, resultId);
  let bugId = result.bugId;
  if (input.bug !== undefined) {
    if (input.bug === null) bugId = null;
    else {
      const n = typeof input.bug === 'number' ? input.bug : bugNumberFrom(input.bug);
      if (n === null) throw new BadRequestError('Enter a bug number, like BUG-12.', 'BAD_BUG_NUMBER');
      const bug = await db.bug.findUnique({ where: { number: n }, select: { id: true } });
      if (!bug) throw new NotFoundError(`${bugKey(n)} was not found.`);
      bugId = bug.id;
    }
  }
  // Only a failure has a bug.
  if (input.outcome !== 'FAIL') bugId = null;
  await db.bugTestResult.update({
    where: { id: result.id },
    data: {
      outcome: input.outcome,
      ...(input.note !== undefined ? { note: input.note } : {}),
      ...(input.outcome === null ? { note: null } : {}),
      bugId,
      testedById: input.outcome === null ? null : actor.id,
      testedAt: input.outcome === null ? null : new Date(),
    },
  });
  return getRun(runId, actor);
}

export async function finishRun(id: string, finished: boolean, actor: BugActor) {
  const r = await loadRun(id);
  if (!!r.finishedAt !== finished) await db.bugTestRun.update({ where: { id }, data: finished ? { finishedAt: new Date(), finishedById: actor.id } : { finishedAt: null, finishedById: null } });
  return getRun(id, actor);
}

/** A run started by mistake: its starter or the super admin removes it. Bugs reported from it stay. */
export async function deleteRun(id: string, actor: BugActor) {
  const r = await loadRun(id);
  if (!mayDelete(r, actor)) throw new ForbiddenError('Only whoever started a run, or the super admin, can delete it.');
  await db.bugTestRun.delete({ where: { id } });
  return { ok: true };
}

// ── A failure reported as a bug ─────────────────────────────────────────────

/** The item a new bug is being reported from: it must be on a run that is still open. */
export async function reportableResult(resultId: string) {
  const result = await db.bugTestResult.findUnique({ where: { id: resultId }, include: { run: true } });
  if (!result) throw new BadRequestError('That test item was not found. Report the bug without it.', 'TEST_ITEM_NOT_FOUND');
  if (result.run.finishedAt) throw new ConflictError('That test run is finished. Reopen it to report a failure from it.', 'RUN_FINISHED');
  return { id: result.id, item: result.title, run: result.run.checklistName };
}

/** The new bug is the item's failure. */
export async function linkReportedBug(tx: Prisma.TransactionClient, resultId: string, bugId: string, actor: BugActor) {
  await tx.bugTestResult.update({ where: { id: resultId }, data: { outcome: 'FAIL', bugId, testedById: actor.id, testedAt: new Date() } });
}

/** The test items a bug is the failure of, for its page. */
export async function testsOf(bugId: string) {
  const rows = await db.bugTestResult.findMany({ where: { bugId }, orderBy: { testedAt: 'desc' }, take: 20, select: { title: true, run: { select: { id: true, checklistName: true } } } });
  return rows.map((r) => ({ runId: r.run.id, checklist: r.run.checklistName, item: r.title }));
}
