import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { BugApp, BugStatus, BugType, Role, type BugRelease } 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 { BUG_APPS } from './bug-modules.service';
import { notify, peopleOn, sendBatch } from './bug-notify.service';
import { bugKey } from './bug-rules';

/**
 * Releases (docs/bug-tracker-plan.md, BT5): one per app and name, "1.4.2" of
 * the Android app or "18 Nov" of the web app.
 *
 * A developer says which release a fix is in; a tester says which release a
 * bug was found in. Marking a release as deployed tells QA its fixes are
 * ready to verify, and the release's page gives its notes from the bugs fixed
 * in it.
 *
 * Everyone on the tracker reads releases. Developers and the super admin add
 * and edit them and mark them deployed; only the super admin archives one.
 * An archived release leaves the choices; the bugs that name it keep it.
 */

export const RELEASE_LIMITS = { name: { min: 1, max: 40 }, notes: 10_000 } as const;

const clean = (v: string) => !/[\u0000-\u001f\u007f]/.test(v);
const name = z
  .string()
  .trim()
  .min(RELEASE_LIMITS.name.min, 'Give the release a name, like 1.4.2 or 18 Nov')
  .max(RELEASE_LIMITS.name.max, `Name must be at most ${RELEASE_LIMITS.name.max} characters`)
  .refine(clean, 'Name must be a single line');
/** A plain day, YYYY-MM-DD; empty or null clears it. */
const day = z.union([z.string(), z.null()]).transform((v, ctx) => {
  const t = (v ?? '').trim();
  if (!t) return null;
  const d = /^\d{4}-\d{2}-\d{2}$/.test(t) ? new Date(`${t}T00:00:00Z`) : null;
  if (!d || Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== t) {
    ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'Enter a real date' });
    return z.NEVER;
  }
  return d;
});
const notes = 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 > RELEASE_LIMITS.notes) ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Notes must be at most ${RELEASE_LIMITS.notes.toLocaleString('en-IN')} characters` });
  return t;
});

export const createReleaseSchema = z
  .object({ app: z.nativeEnum(BugApp, { errorMap: () => ({ message: 'Choose the app' }) }), name, plannedFor: day.optional(), notes: notes.optional() })
  .strict();
/** The app is not editable: the bugs that name a release are bugs in that app. */
export const updateReleaseSchema = z
  .object({ name, plannedFor: day, notes })
  .partial()
  .strict()
  .refine((v) => Object.keys(v).length > 0, 'Nothing to update');

const appLabel = (app: BugApp) => BUG_APPS.find((a) => a.key === app)?.label ?? app;
/** "Web app 18 Nov": how a release is named where its app isn't already clear. */
export const releaseLabel = (r: Pick<BugRelease, 'app' | 'name'>) => `${appLabel(r.app)} ${r.name}`;
const dayOf = (d: Date | null) => (d ? d.toISOString().slice(0, 10) : null);

function mayEdit(actor: BugActor) {
  if (actor.role !== Role.DEVELOPER && actor.role !== Role.SUPER_ADMIN) throw new ForbiddenError('Only a developer or the super admin can change releases.');
}

async function load(id: string) {
  const r = await db.bugRelease.findUnique({ where: { id } });
  if (!r) throw new NotFoundError('That release was not found.');
  return r;
}

async function assertFreeName(app: BugApp, value: string, exceptId?: string) {
  const taken = await db.bugRelease.findFirst({ where: { app, name: { equals: value, mode: 'insensitive' }, ...(exceptId ? { id: { not: exceptId } } : {}) }, select: { archivedAt: true } });
  if (taken) throw new ConflictError(taken.archivedAt ? `${appLabel(app)} already has a release with that name, archived. Restore it instead.` : `${appLabel(app)} already has a release with that name.`, 'RELEASE_EXISTS');
}

/** A release a bug may be given: it exists, is for the bug's app, and is not archived. */
export async function usableRelease(id: string, app: BugApp, what: 'fix' | 'found') {
  const r = await db.bugRelease.findUnique({ where: { id } });
  if (!r) throw new BadRequestError('Choose a release from the list.', 'RELEASE_NOT_FOUND');
  if (r.app !== app) throw new BadRequestError(`That release is for the ${appLabel(r.app)}; this bug is in the ${appLabel(app)}.`, 'RELEASE_WRONG_APP');
  if (r.archivedAt) throw new BadRequestError(what === 'fix' ? 'That release is archived. Choose another.' : 'That release is archived. Choose another, or type the version.', 'RELEASE_ARCHIVED');
  return r;
}

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

type Counts = { fixed: number; waiting: number; verified: number; sentBack: number; found: number };

function present(r: BugRelease, counts?: Counts, who?: Map<string, string>) {
  return {
    id: r.id,
    app: r.app,
    name: r.name,
    label: releaseLabel(r),
    plannedFor: dayOf(r.plannedFor),
    notes: r.notes,
    deployed: !!r.deployedAt,
    deployedAt: r.deployedAt,
    deployedBy: r.deployedById && who ? { id: r.deployedById, name: who.get(r.deployedById) ?? 'Unknown' } : null,
    archived: !!r.archivedAt,
    createdAt: r.createdAt,
    ...(counts ? { counts } : {}),
  };
}

async function countsFor(ids: string[]): Promise<Map<string, Counts>> {
  const out = new Map<string, Counts>(ids.map((id) => [id, { fixed: 0, waiting: 0, verified: 0, sentBack: 0, found: 0 }]));
  if (!ids.length) return out;
  const [fixed, found] = await Promise.all([
    db.bug.groupBy({ by: ['fixedInReleaseId', 'status'], where: { fixedInReleaseId: { in: ids } }, _count: { _all: true } }),
    db.bug.groupBy({ by: ['foundInReleaseId'], where: { foundInReleaseId: { in: ids } }, _count: { _all: true } }),
  ]);
  for (const f of fixed) {
    const c = out.get(f.fixedInReleaseId!)!;
    c.fixed += f._count._all;
    if (f.status === BugStatus.FIXED) c.waiting += f._count._all;
    else if (f.status === BugStatus.CLOSED) c.verified += f._count._all;
    else c.sentBack += f._count._all;
  }
  for (const f of found) out.get(f.foundInReleaseId!)!.found = f._count._all;
  return out;
}

/** What is coming first (soonest planned day first), then what went out, newest first. */
const order = (a: BugRelease, b: BugRelease) => {
  if (!a.deployedAt !== !b.deployedAt) return a.deployedAt ? 1 : -1;
  if (a.deployedAt && b.deployedAt) return b.deployedAt.getTime() - a.deployedAt.getTime();
  const [x, y] = [a.plannedFor?.getTime() ?? Infinity, b.plannedFor?.getTime() ?? Infinity];
  return x - y || b.createdAt.getTime() - a.createdAt.getTime();
};

export async function listReleases(f: { app?: BugApp; includeArchived?: boolean } = {}) {
  const rows = (await db.bugRelease.findMany({ where: { ...(f.app ? { app: f.app } : {}), ...(f.includeArchived ? {} : { archivedAt: null }) }, take: 500, orderBy: { createdAt: 'desc' } })).sort(order);
  const counts = await countsFor(rows.map((r) => r.id));
  return rows.map((r) => present(r, counts.get(r.id)));
}

/** The releases a bug can be given, for the forms: every one not archived, lightly. */
export async function releaseChoices() {
  const rows = (await db.bugRelease.findMany({ where: { archivedAt: null }, take: 300, orderBy: { createdAt: 'desc' } })).sort(order);
  return rows.map((r) => ({ id: r.id, app: r.app, name: r.name, deployed: !!r.deployedAt, deployedAt: r.deployedAt, plannedFor: dayOf(r.plannedFor) }));
}

const BUG_LINE = { number: true, title: true, type: true, status: true, resolution: true, severity: true, assigneeId: true, module: { select: { name: true } } } as const;

export async function getRelease(id: string) {
  const r = await load(id);
  const [fixed, found, counts] = await Promise.all([
    db.bug.findMany({ where: { fixedInReleaseId: id }, select: BUG_LINE, orderBy: [{ severity: 'asc' }, { number: 'asc' }], take: 500 }),
    db.bug.findMany({ where: { foundInReleaseId: id }, select: BUG_LINE, orderBy: [{ severity: 'asc' }, { number: 'asc' }], take: 500 }),
    countsFor([id]),
  ]);
  const ids = [...new Set([r.deployedById, ...fixed.map((b) => b.assigneeId), ...found.map((b) => b.assigneeId)].filter((v): v is string => !!v))];
  const who = new Map((await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  const line = (b: (typeof fixed)[number]) => ({
    number: b.number,
    key: bugKey(b.number),
    title: b.title,
    type: b.type,
    status: b.status,
    resolution: b.resolution,
    severity: b.severity,
    module: b.module.name,
    assignee: b.assigneeId ? { id: b.assigneeId, name: who.get(b.assigneeId) ?? 'Unknown' } : null,
  });
  return { ...present(r, counts.get(id), who), fixed: fixed.map(line), found: found.map(line), releaseNotes: releaseNotes(r, fixed) };
}

/**
 * The release's notes, from the bugs fixed in it: fixes, then improvements
 * (suggestions). A fix QA sent back is left out until it is fixed again.
 */
function releaseNotes(r: BugRelease, fixed: { number: number; title: string; type: BugType; status: BugStatus; resolution: string | null }[]): string {
  const held = fixed.filter((b) => (b.status === BugStatus.FIXED && !b.resolution) || (b.status === BugStatus.CLOSED && b.resolution === 'VERIFIED'));
  const part = (heading: string, type: BugType) => {
    const rows = held.filter((b) => b.type === type);
    return rows.length ? [`### ${heading}`, ...rows.map((b) => `- ${b.title} (${bugKey(b.number)})`), ''] : [];
  };
  const when = r.deployedAt ? `Released ${r.deployedAt.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'Asia/Kolkata' })}` : r.plannedFor ? `Planned for ${r.plannedFor.toLocaleDateString('en-IN', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })}` : 'Not released yet';
  return [`## ${releaseLabel(r)}`, when, '', ...(r.notes ? [r.notes, ''] : []), ...part('Fixed', BugType.BUG), ...part('Improved', BugType.SUGGESTION), ...(held.length ? [] : ['No fixes recorded in this release yet.', ''])]
    .join('\n')
    .trim();
}

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

export async function createRelease(input: z.infer<typeof createReleaseSchema>, actor: BugActor) {
  mayEdit(actor);
  await assertFreeName(input.app, input.name);
  const r = await db.bugRelease.create({ data: { app: input.app, name: input.name, plannedFor: input.plannedFor ?? null, notes: input.notes ?? null, createdById: actor.id } });
  return getRelease(r.id);
}

export async function updateRelease(id: string, input: z.infer<typeof updateReleaseSchema>, actor: BugActor) {
  mayEdit(actor);
  const r = await load(id);
  const renamed = input.name !== undefined && input.name !== r.name;
  if (renamed) await assertFreeName(r.app, input.name!, id);
  await db.$transaction([
    db.bugRelease.update({ where: { id }, data: input }),
    // The bugs carry the release's name as text (the export, the emails): keep it in step.
    ...(renamed ? [db.bug.updateMany({ where: { fixedInReleaseId: id }, data: { fixedIn: input.name } }), db.bug.updateMany({ where: { foundInReleaseId: id }, data: { appVersion: input.name } })] : []),
  ]);
  return getRelease(id);
}

/**
 * Deployed: the fixes in it can be verified now. Each waiting bug's thread
 * says so, and its followers and every tester are told (one email each, for
 * the lot). Taking the mark back (a mistake, a rollback) tells nobody.
 */
export async function setDeployed(id: string, deployed: boolean, actor: BugActor) {
  mayEdit(actor);
  const r = await load(id);
  if (!!r.deployedAt === deployed) return getRelease(id);
  if (r.archivedAt) throw new ConflictError('This release is archived. Restore it first.', 'RELEASE_ARCHIVED');
  const waiting = await db.bug.findMany({ where: { fixedInReleaseId: id, status: BugStatus.FIXED }, select: { id: true, assigneeId: true } });
  const label = releaseLabel(r);
  await db.$transaction([
    db.bugRelease.update({ where: { id }, data: deployed ? { deployedAt: new Date(), deployedById: actor.id } : { deployedAt: null, deployedById: null } }),
    ...waiting.map((b) => db.bugEvent.create({ data: { bugId: b.id, actorId: actor.id, type: deployed ? 'DEPLOYED' : 'UNDEPLOYED', changes: { release: label } } })),
    ...(waiting.length ? [db.bug.updateMany({ where: { id: { in: waiting.map((b) => b.id) } }, data: { lastActivityAt: new Date() } })] : []),
  ]);
  if (deployed && waiting.length) {
    const testers = (await db.user.findMany({ where: { role: Role.QA, deactivatedAt: null }, select: { id: true } })).map((u) => u.id);
    const batchId = randomUUID();
    for (const b of waiting) {
      const to = [...new Set([...(await peopleOn(b.id, b.assigneeId)), ...testers])];
      await notify({ bugId: b.id, actor, to: to.map((userId) => ({ userId, kind: 'DEPLOYED' as const })), snippet: label, batchId });
    }
    sendBatch(batchId);
  }
  return getRelease(id);
}

export async function setArchived(id: string, archived: boolean, actor: BugActor) {
  if (actor.role !== Role.SUPER_ADMIN) throw new ForbiddenError('Only the super admin can archive a release.');
  const r = await load(id);
  if (!!r.archivedAt !== archived) await db.bugRelease.update({ where: { id }, data: { archivedAt: archived ? new Date() : null } });
  return getRelease(id);
}
