import { BugStatus, Role } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { env } from '../../config/env';
import { GITHUB_ACTOR, type BugActor } from './bug-access';
import { bugKey, moveSchema } from './bug-rules';
import { moveBug } from './bug-workflow.service';

/**
 * GitHub tells the tracker about code (docs/bug-tracker-plan.md, BT6).
 *
 * A commit or pull request whose text names a bug is linked to it: the bug's
 * page shows the change. One that says "Fixes BUG-12" (or closes, resolves)
 * also moves the bug to Fixed once it is merged: the pull request is merged
 * into a main branch, or the commit is pushed to one. From there QA verifies
 * it like any other fix.
 *
 * The fix is credited to the developer who wrote it, matched by the GitHub
 * username they gave the tracker or by their email; with nobody to match, to
 * "GitHub". It goes into the app's coming release when there is exactly one.
 *
 * Everything GitHub sends is data, never instructions: only bug numbers and
 * the words before them are read from it; the links are built here from the
 * repository's name and the commit's hash, not taken from the payload.
 *
 * GitHub repeats deliveries; each is recorded by its id and handled once, and
 * a change moves a bug to Fixed at most once (BugCodeLink.appliedAt), so a
 * bug QA reopened is not "fixed" again by an old event.
 */

const WORKABLE: BugStatus[] = [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.REOPENED, BugStatus.NEEDS_INFO];
const MAX_REFS = 20;
const MAX_COMMITS = 100;

const FIXING = /\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?)\b[\s:]*((?:bug[-\s]?\d{1,9}(?:\s*(?:,|and|&)\s*)?)+)/gi;
const ANY = /\bbug-(\d{1,9})\b/gi;

/** The bugs a commit message or pull request names, and whether it says it fixes them. */
export function bugRefs(text: string): { number: number; fixes: boolean }[] {
  const out = new Map<number, boolean>();
  for (const m of text.matchAll(ANY)) out.set(Number(m[1]), false);
  for (const m of text.matchAll(FIXING)) for (const n of m[1].matchAll(/\d{1,9}/g)) out.set(Number(n[0]), true);
  return [...out.entries()].slice(0, MAX_REFS).map(([number, fixes]) => ({ number, fixes }));
}

const firstLine = (text: string) => (text.split('\n')[0] ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 200) || '(no message)';
const REPO = /^[\w.-]{1,100}\/[\w.-]{1,100}$/;
const SHA = /^[0-9a-f]{40}$/;
const str = (v: unknown, max = 200): string | null => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null);

interface Change {
  kind: 'COMMIT' | 'PULL_REQUEST';
  repo: string;
  /** The commit's hash, or the pull request's number. */
  ref: string;
  title: string;
  /** The text read for bug numbers. */
  text: string;
  author: string | null;
  authorEmail: string | null;
  branch: string | null;
  /** A pull request: OPEN | MERGED | CLOSED. A commit: PUSHED | MERGED. */
  state: string;
  /** It is on a main branch now. */
  merged: boolean;
}

const urlOf = (c: Pick<Change, 'kind' | 'repo' | 'ref'>) => `https://github.com/${c.repo}/${c.kind === 'COMMIT' ? `commit/${c.ref}` : `pull/${c.ref}`}`;
const named = (c: Pick<Change, 'kind' | 'repo' | 'ref'>) => `${c.kind === 'COMMIT' ? `commit ${c.ref.slice(0, 7)}` : `pull request #${c.ref}`} in ${c.repo}`;

/** The developer a change belongs to, or "GitHub" when nobody on the team matches. */
async function actorFor(login: string | null, email: string | null): Promise<BugActor> {
  const fixer = { role: { in: [Role.DEVELOPER, Role.SUPER_ADMIN] }, deactivatedAt: null };
  if (login) {
    const p = await db.bugNotifyPrefs.findUnique({ where: { githubLogin: login.toLowerCase() }, select: { userId: true } });
    const u = p ? await db.user.findFirst({ where: { id: p.userId, ...fixer }, select: { id: true, name: true, role: true } }) : null;
    if (u) return u;
  }
  if (email) {
    const u = await db.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, ...fixer }, select: { id: true, name: true, role: true } });
    if (u) return u;
  }
  return GITHUB_ACTOR;
}

/** Link one change to one bug; move the bug to Fixed if this is the moment for it. */
async function apply(c: Change, ref: { number: number; fixes: boolean }): Promise<{ linked: boolean; fixed: boolean }> {
  const bug = await db.bug.findUnique({ where: { number: ref.number }, select: { id: true, number: true, app: true, status: true } });
  if (!bug) return { linked: false, fixed: false };
  const key = { bugId_kind_repo_ref: { bugId: bug.id, kind: c.kind, repo: c.repo, ref: c.ref } };
  const before = await db.bugCodeLink.findUnique({ where: key });
  // A commit that reached a main branch stays "merged", whatever branch it is seen on next.
  const state = before?.state === 'MERGED' && c.kind === 'COMMIT' ? 'MERGED' : c.state;
  const fixes = (before?.fixes ?? false) || ref.fixes;
  const actor = await actorFor(c.author, c.authorEmail);
  if (!before) {
    await db.$transaction([
      db.bugCodeLink.create({ data: { bugId: bug.id, kind: c.kind, repo: c.repo, ref: c.ref, url: urlOf(c), title: c.title, author: c.author, branch: c.branch, fixes, state } }),
      db.bugEvent.create({ data: { bugId: bug.id, actorId: actor.id, type: 'CODE_LINKED', changes: { kind: c.kind, repo: c.repo, ref: c.kind === 'COMMIT' ? c.ref.slice(0, 7) : `#${c.ref}`, title: c.title, url: urlOf(c), fixes } } }),
      db.bug.update({ where: { id: bug.id }, data: { lastActivityAt: new Date() } }),
    ]);
  } else {
    await db.bugCodeLink.update({ where: { id: before.id }, data: { title: c.title, state, fixes, branch: c.branch ?? before.branch } });
  }

  let fixed = false;
  if (fixes && c.merged && !before?.appliedAt) {
    // Whatever happens next, this change has had its one go at moving the bug.
    await db.bugCodeLink.update({ where: key, data: { appliedAt: new Date() } });
    if (WORKABLE.includes(bug.status)) {
      const coming = await db.bugRelease.findMany({ where: { app: bug.app, archivedAt: null, deployedAt: null }, select: { id: true }, take: 2 });
      const input = moveSchema.parse({ action: 'fix', note: `Fixed by ${named(c)}: ${c.title}`, fixLink: urlOf(c), ...(coming.length === 1 ? { fixedInReleaseId: coming[0].id } : {}) });
      try {
        await moveBug(bug.number, input, actor);
        fixed = true;
      } catch (err) {
        // Someone moved the bug in the same moment: the link is there, the status is theirs.
        // eslint-disable-next-line no-console
        console.warn(`[bugs] GitHub could not mark ${bugKey(bug.number)} as fixed: ${err instanceof Error ? err.message : String(err)}`);
      }
    }
  }
  return { linked: !before, fixed };
}

async function applyAll(changes: Change[]) {
  let linked = 0;
  let fixed = 0;
  for (const c of changes) {
    for (const ref of bugRefs(c.text)) {
      const r = await apply(c, ref);
      if (r.linked) linked++;
      if (r.fixed) fixed++;
    }
  }
  return { linked, fixed };
}

type Json = Record<string, unknown>;
const obj = (v: unknown): Json => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Json) : {});

function fromPush(body: Json, repo: string, main: Set<string>): Change[] {
  const ref = str(body.ref) ?? '';
  if (!ref.startsWith('refs/heads/') || body.deleted === true) return [];
  const branch = ref.slice('refs/heads/'.length);
  const merged = main.has(branch);
  const commits = Array.isArray(body.commits) ? body.commits.slice(0, MAX_COMMITS) : [];
  return commits.flatMap((raw): Change[] => {
    const c = obj(raw);
    const sha = str(c.id) ?? '';
    const message = typeof c.message === 'string' ? c.message.slice(0, 20_000) : '';
    if (!SHA.test(sha) || !message) return [];
    const author = obj(c.author);
    return [{ kind: 'COMMIT', repo, ref: sha, title: firstLine(message), text: message, author: str(author.username, 60) ?? str(author.name, 60), authorEmail: str(author.email, 200), branch, state: merged ? 'MERGED' : 'PUSHED', merged }];
  });
}

function fromPullRequest(body: Json, repo: string, main: Set<string>): Change[] {
  const pr = obj(body.pull_request);
  const number = typeof pr.number === 'number' && Number.isInteger(pr.number) && pr.number > 0 ? String(pr.number) : null;
  const action = str(body.action) ?? '';
  if (!number || !['opened', 'edited', 'reopened', 'closed', 'ready_for_review'].includes(action)) return [];
  const title = typeof pr.title === 'string' ? pr.title : '';
  const text = `${title}\n${typeof pr.body === 'string' ? pr.body.slice(0, 20_000) : ''}`;
  const base = str(obj(pr.base).ref) ?? '';
  const wasMerged = pr.merged === true;
  const merged = wasMerged && main.has(base);
  // A merged pull request belongs to whoever opened it: they wrote the fix.
  return [{ kind: 'PULL_REQUEST', repo, ref: number, title: firstLine(title), text, author: str(obj(pr.user).login, 60), authorEmail: null, branch: str(obj(pr.head).ref, 200), state: wasMerged ? 'MERGED' : pr.state === 'closed' ? 'CLOSED' : 'OPEN', merged }];
}

export interface GithubOutcome {
  ok: true;
  /** What was done with it, in a word, for GitHub's delivery log. */
  result: 'pong' | 'handled' | 'ignored' | 'duplicate';
  linked: number;
  fixed: number;
  note?: string;
}

/** One delivery from GitHub, already checked against the secret. */
export async function handleGithub(event: string, deliveryId: string, body: unknown): Promise<GithubOutcome> {
  const payload = obj(body);
  if (event === 'ping') return { ok: true, result: 'pong', linked: 0, fixed: 0 };
  const repository = obj(payload.repository);
  const repo = str(repository.full_name) ?? '';
  const none = (note: string): GithubOutcome => ({ ok: true, result: 'ignored', linked: 0, fixed: 0, note });
  if (!REPO.test(repo)) return none('No repository named');
  if (env.BUG_GITHUB_REPOS.length && !env.BUG_GITHUB_REPOS.includes(repo.toLowerCase())) return none('This repository is not on the list');

  // Each delivery once: GitHub repeats them, and people press "Redeliver".
  const first = await db.bugGithubDelivery.createMany({ data: { id: deliveryId, event: event.slice(0, 40), repo }, skipDuplicates: true });
  if (first.count === 0) return { ok: true, result: 'duplicate', linked: 0, fixed: 0 };
  try {
    const main = new Set([...env.BUG_GITHUB_MERGED_BRANCHES, ...(str(repository.default_branch) ? [str(repository.default_branch)!] : [])]);
    const changes = event === 'push' ? fromPush(payload, repo, main) : event === 'pull_request' ? fromPullRequest(payload, repo, main) : null;
    if (!changes) {
      await db.bugGithubDelivery.update({ where: { id: deliveryId }, data: { note: 'Not a push or a pull request' } });
      return none('Not a push or a pull request');
    }
    const done = await applyAll(changes);
    await db.bugGithubDelivery.update({ where: { id: deliveryId }, data: done });
    return { ok: true, result: 'handled', ...done };
  } catch (err) {
    // Not handled: forget the delivery, so GitHub's retry (or "Redeliver") gets a full go.
    await db.bugGithubDelivery.deleteMany({ where: { id: deliveryId } });
    throw err;
  }
}

/** For the super admin: is the webhook set up, and is it arriving? */
export async function githubStatus() {
  const [recent, links] = await Promise.all([db.bugGithubDelivery.findMany({ orderBy: { receivedAt: 'desc' }, take: 10 }), db.bugCodeLink.count()]);
  return {
    configured: !!env.BUG_GITHUB_WEBHOOK_SECRET,
    /** Where each repository's webhook points, after the API's own address. */
    path: '/api/webhooks/github',
    repos: env.BUG_GITHUB_REPOS,
    mergedBranches: env.BUG_GITHUB_MERGED_BRANCHES,
    links,
    recent: recent.map((d) => ({ id: d.id, event: d.event, repo: d.repo, linked: d.linked, fixed: d.fixed, note: d.note, receivedAt: d.receivedAt })),
  };
}

/** The job: delivery records older than 30 days go. */
export async function purgeDeliveries(now = new Date()): Promise<number> {
  return (await db.bugGithubDelivery.deleteMany({ where: { receivedAt: { lt: new Date(now.getTime() - 30 * 86_400_000) } } })).count;
}
