import express, { Router, type Request, type Response } from 'express';
import { z } from 'zod';
import { BugApp } from '@prisma/client';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { rateLimit } from '../../middleware/rateLimit';
import * as invites from '../crm/crm-invites.service';
import { bugActorOf, requireBugAccess, requireSuperAdmin, TRACKER_ROLES } from './bug-access';
import * as team from './bug-team.service';
import * as modules from './bug-modules.service';
import * as bugs from './bug-bugs.service';
import * as files from './bug-files.service';
import * as workflow from './bug-workflow.service';
import * as notes from './bug-notify.service';
import * as insights from './bug-insights.service';
import * as releases from './bug-releases.service';
import * as testing from './bug-testing.service';
import * as checklistIo from './bug-checklist-io.service';
import * as github from './bug-github.service';
import { XLSX_MIME } from '../../lib/xlsx';
import { assignSchema, BUG_LIMITS, bugNumberFrom, bulkSchema, commentSchema, createBugSchema, editCommentSchema, listBugsSchema, moveSchema, updateBugSchema } from './bug-rules';
import { BadRequestError } from '../../lib/errors';

/**
 * The bug tracker (docs/bug-tracker-plan.md). BT1: accounts and settings. BT2: bugs.
 * BT3: the fix-and-verify moves, assignment, bulk changes and "My work".
 * BT4: notifications (the bell and the email switches), the dashboard, the Excel export.
 * BT5: releases (everyone reads; developers and the super admin write) and the board.
 * BT6: test checklists (QA and the super admin write) and runs (anyone on the tracker);
 *      a member's GitHub username; the super admin's view of the GitHub webhook.
 *      (The webhook itself is /api/webhooks/github: bug-github.webhook.ts.)
 *
 *   /api/bug-tracker/invites/:token   public: the set-password page behind an invite
 *   /api/bug-tracker/workspace        SUPER_ADMIN + QA + DEVELOPER
 *   /api/bug-tracker/bugs, /files,
 *     /comments                       SUPER_ADMIN + QA + DEVELOPER (who may edit what: bug-bugs.service)
 *   /api/bug-tracker/team, /modules   SUPER_ADMIN only (everyone reads modules through /workspace)
 *
 * A QA or DEVELOPER account can reach nothing else (authenticate's fence), and
 * no hostel, CRM or blog account ever gets past requireBugAccess.
 */
export const bugTrackerRouter = Router();

const idParam = z.object({ id: z.string().uuid('Invalid id') });
const text = (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) => !/[\u0000-\u001f\u007f]/.test(v), `${label} contains invalid characters`);
const email = z.string().trim().toLowerCase().email('Enter a valid email address').max(160, 'Email must be at most 160 characters');
const phone = z.string().trim().max(20, 'Phone must be at most 20 characters').regex(/^[0-9+()\-\s]*$/, 'Phone can only have digits, spaces, +, - and brackets');
const role = z.enum(TRACKER_ROLES, { errorMap: () => ({ message: 'Choose QA or Developer' }) });

// ── Public: the set-password page behind a member's invite link ────────────

const inviteLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 30, name: 'bug-invite' });
const acceptSchema = z.object({
  password: z.string().min(8, 'Password must be at least 8 characters').max(200, 'Password must be at most 200 characters'),
});

bugTrackerRouter.get(
  '/invites/:token',
  inviteLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ invite: await invites.lookupInvite(String(req.params.token)) });
  }),
);
bugTrackerRouter.post(
  '/invites/:token/accept',
  inviteLimiter,
  asyncHandler(async (req: Request, res: Response) => {
    const { password } = acceptSchema.parse(req.body);
    res.json(await invites.acceptInvite(String(req.params.token), password));
  }),
);

// ── Everything else: the super admin, QA and developers ────────────────────

bugTrackerRouter.use(authenticate, requireBugAccess);

/** What the workspace needs to draw itself: who I am, where bugs are filed, who is on the team. */
bugTrackerRouter.get(
  '/workspace',
  asyncHandler(async (_req: Request, res: Response) => {
    const [mods, members, rels] = await Promise.all([modules.listModules(), team.activeMembers(), releases.releaseChoices()]);
    res.json({ me: bugActorOf(res), apps: modules.BUG_APPS, modules: mods, members, releases: rels });
  }),
);

// ── Bugs ───────────────────────────────────────────────────────────────────

/** ":number" in a path: 12 or BUG-12. */
const numberOf = (req: Request): number => {
  const n = bugNumberFrom(String(req.params.number));
  if (n === null) throw new BadRequestError('That is not a bug number.', 'BAD_BUG_NUMBER');
  return n;
};

bugTrackerRouter.get(
  '/bugs',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await bugs.listBugs(listBugsSchema.parse(req.query)));
  }),
);
bugTrackerRouter.get(
  '/bugs/similar',
  asyncHandler(async (req: Request, res: Response) => {
    const q = z.object({ title: z.string().trim().max(200), except: z.coerce.number().int().positive().optional() }).parse(req.query);
    res.json(await bugs.similarBugs(q.title, q.except));
  }),
);
bugTrackerRouter.post(
  '/bugs',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ bug: await bugs.createBug(createBugSchema.parse(req.body), bugActorOf(res)) });
  }),
);
// Several bugs at once: assign, set priority, close as duplicates. Each bug
// follows the same rules as one at a time and reports its own result.
bugTrackerRouter.post(
  '/bugs/bulk',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await workflow.bulk(bulkSchema.parse(req.body), bugActorOf(res)));
  }),
);
/** What waits on me, by role: the "My work" page and the number beside it. */
bugTrackerRouter.get(
  '/my-work',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await workflow.myWork(bugActorOf(res)));
  }),
);
// The numbers in the menu: bugs waiting on me, and what I haven't read.
bugTrackerRouter.get(
  '/my-work/count',
  asyncHandler(async (_req: Request, res: Response) => {
    const actor = bugActorOf(res);
    const [attention, unread] = await Promise.all([workflow.attentionCount(actor), notes.unreadCount(actor)]);
    res.json({ attention, unread });
  }),
);
/** The bug list as filtered on screen, as an Excel file. */
bugTrackerRouter.get(
  '/bugs/export',
  asyncHandler(async (req: Request, res: Response) => {
    const file = await insights.exportBugs(listBugsSchema.parse(req.query));
    res.setHeader('Content-Type', XLSX_MIME);
    res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
    res.send(file.bytes);
  }),
);
/** The bugs as cards under their status, with the moves I may make on each. */
bugTrackerRouter.get(
  '/board',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await workflow.board(listBugsSchema.parse(req.query), bugActorOf(res)));
  }),
);

// ── Releases: everyone reads; who may write is the service's rule ──────────

bugTrackerRouter.get(
  '/releases',
  asyncHandler(async (req: Request, res: Response) => {
    const f = z.object({ app: z.nativeEnum(BugApp).optional(), archived: z.enum(['true', 'false']).default('false') }).parse(req.query);
    res.json({ releases: await releases.listReleases({ app: f.app, includeArchived: f.archived === 'true' }) });
  }),
);
bugTrackerRouter.post(
  '/releases',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ release: await releases.createRelease(releases.createReleaseSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.get(
  '/releases/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ release: await releases.getRelease(idParam.parse(req.params).id) });
  }),
);
bugTrackerRouter.patch(
  '/releases/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ release: await releases.updateRelease(idParam.parse(req.params).id, releases.updateReleaseSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/releases/:id/deployed',
  asyncHandler(async (req: Request, res: Response) => {
    const { deployed } = z.object({ deployed: z.boolean() }).strict().parse(req.body);
    res.json({ release: await releases.setDeployed(idParam.parse(req.params).id, deployed, bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/releases/:id/archived',
  asyncHandler(async (req: Request, res: Response) => {
    const { archived } = z.object({ archived: z.boolean() }).strict().parse(req.body);
    res.json({ release: await releases.setArchived(idParam.parse(req.params).id, archived, bugActorOf(res)) });
  }),
);

/** Where the bugs stand; the super admin also gets each developer's numbers. */
bugTrackerRouter.get(
  '/dashboard',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await insights.dashboard(bugActorOf(res)));
  }),
);

// ── Notifications: mine only ───────────────────────────────────────────────

bugTrackerRouter.get(
  '/notifications',
  asyncHandler(async (req: Request, res: Response) => {
    const f = z
      .object({ page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(100).default(25), unread: z.enum(['true', 'false']).default('false') })
      .parse(req.query);
    res.json(await notes.listNotifications(bugActorOf(res), { page: f.page, limit: f.limit, unread: f.unread === 'true' }));
  }),
);
bugTrackerRouter.post(
  '/notifications/read',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z
      .object({ ids: z.array(z.string().uuid()).max(200).optional(), all: z.boolean().optional() })
      .refine((v) => v.all || (v.ids?.length ?? 0) > 0, 'Say which notifications to mark as read')
      .parse(req.body);
    res.json(await notes.markRead(bugActorOf(res), input));
  }),
);
bugTrackerRouter.get(
  '/notifications/settings',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await notes.getPrefs(bugActorOf(res)));
  }),
);
bugTrackerRouter.put(
  '/notifications/settings',
  asyncHandler(async (req: Request, res: Response) => {
    const { emailOff } = z.object({ emailOff: z.array(z.enum(notes.EMAIL_SWITCHES)).max(notes.EMAIL_SWITCHES.length) }).parse(req.body);
    res.json(await notes.setPrefs(bugActorOf(res), emailOff));
  }),
);

/** BT6: my GitHub username, so my commits and pull requests are mine here. Null clears it. */
bugTrackerRouter.put(
  '/notifications/github',
  asyncHandler(async (req: Request, res: Response) => {
    const { login } = z
      .object({
        login: z.union([
          z
            .string()
            .trim()
            .regex(/^@?[a-zA-Z\d](?:[a-zA-Z\d]|-(?=[a-zA-Z\d])){0,38}$/, 'That is not a GitHub username')
            .transform((v) => v.replace(/^@/, '')),
          z.null(),
        ]),
      })
      .strict()
      .parse(req.body);
    res.json(await notes.setGithubLogin(bugActorOf(res), login));
  }),
);
/** BT6: is GitHub's webhook set up, and is it arriving? */
bugTrackerRouter.get(
  '/github',
  requireSuperAdmin,
  asyncHandler(async (_req: Request, res: Response) => {
    res.json(await github.githubStatus());
  }),
);

// ── Test checklists and runs (BT6): who may write is the service's rule ────

bugTrackerRouter.get(
  '/checklists',
  asyncHandler(async (req: Request, res: Response) => {
    const f = z.object({ archived: z.enum(['true', 'false']).default('false') }).parse(req.query);
    res.json({ checklists: await testing.listChecklists({ includeArchived: f.archived === 'true' }) });
  }),
);
/** Checklists as an Excel file: all of them, or the ones named (?ids=a,b). Anyone on the tracker. */
bugTrackerRouter.get(
  '/checklists/export',
  asyncHandler(async (req: Request, res: Response) => {
    const f = z
      .object({
        ids: z
          .string()
          .optional()
          .transform((v) => (v ? v.split(',').map((x) => x.trim()).filter(Boolean) : []))
          .pipe(z.array(z.string().uuid('Invalid id')).max(500)),
        archived: z.enum(['true', 'false']).default('false'),
      })
      .parse(req.query);
    const file = await checklistIo.exportChecklists({ ids: f.ids, includeArchived: f.archived === 'true' });
    res.setHeader('Content-Type', XLSX_MIME);
    res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
    res.send(file.bytes);
  }),
);
/** An example file to fill in. */
bugTrackerRouter.get(
  '/checklists/template',
  asyncHandler(async (_req: Request, res: Response) => {
    const file = checklistIo.templateWorkbook();
    res.setHeader('Content-Type', XLSX_MIME);
    res.setHeader('Content-Disposition', `attachment; filename="${file.filename}"`);
    res.send(file.bytes);
  }),
);
/** Checklists from a sheet the browser read: looked at first (dryRun), then written all at once. QA and the super admin. */
bugTrackerRouter.post(
  '/checklists/import',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await checklistIo.importChecklists(checklistIo.importSchema.parse(req.body), bugActorOf(res)));
  }),
);
bugTrackerRouter.post(
  '/checklists',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ checklist: await testing.createChecklist(testing.createChecklistSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.get(
  '/checklists/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ checklist: await testing.getChecklist(idParam.parse(req.params).id) });
  }),
);
bugTrackerRouter.patch(
  '/checklists/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ checklist: await testing.updateChecklist(idParam.parse(req.params).id, testing.updateChecklistSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.get(
  '/runs',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await testing.listRuns(testing.listRunsSchema.parse(req.query)));
  }),
);
bugTrackerRouter.post(
  '/runs',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ run: await testing.startRun(testing.startRunSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.get(
  '/runs/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ run: await testing.getRun(idParam.parse(req.params).id, bugActorOf(res)) });
  }),
);
bugTrackerRouter.delete(
  '/runs/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await testing.deleteRun(idParam.parse(req.params).id, bugActorOf(res)));
  }),
);
bugTrackerRouter.put(
  '/runs/:id/results/:resultId',
  asyncHandler(async (req: Request, res: Response) => {
    const p = z.object({ id: z.string().uuid('Invalid id'), resultId: z.string().uuid('Invalid id') }).parse(req.params);
    res.json({ run: await testing.recordResult(p.id, p.resultId, testing.resultSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/runs/:id/finished',
  asyncHandler(async (req: Request, res: Response) => {
    const { finished } = z.object({ finished: z.boolean() }).strict().parse(req.body);
    res.json({ run: await testing.finishRun(idParam.parse(req.params).id, finished, bugActorOf(res)) });
  }),
);

bugTrackerRouter.get(
  '/bugs/:number',
  asyncHandler(async (req: Request, res: Response) => {
    const actor = bugActorOf(res);
    const bug = await bugs.getBug(numberOf(req), actor);
    // Opening a bug reads what I was told about it.
    await notes.markBugRead(actor, bug.id);
    res.json({ bug });
  }),
);
bugTrackerRouter.patch(
  '/bugs/:number',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await bugs.updateBug(numberOf(req), updateBugSchema.parse(req.body), bugActorOf(res)) });
  }),
);
// A move through the fix-and-verify loop: start, ask, answer, fix, suggest, close, reopen.
bugTrackerRouter.post(
  '/bugs/:number/move',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await workflow.moveBug(numberOf(req), moveSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/bugs/:number/assign',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await workflow.assignBug(numberOf(req), assignSchema.parse(req.body).assigneeId, bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/bugs/:number/files',
  asyncHandler(async (req: Request, res: Response) => {
    const { attachmentIds } = z.object({ attachmentIds: z.array(z.string().uuid()).min(1).max(BUG_LIMITS.filesPerItem) }).parse(req.body);
    res.json({ bug: await bugs.addFiles(numberOf(req), [...new Set(attachmentIds)], bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/bugs/:number/comments',
  asyncHandler(async (req: Request, res: Response) => {
    res.status(201).json({ bug: await bugs.addComment(numberOf(req), commentSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/bugs/:number/watch',
  asyncHandler(async (req: Request, res: Response) => {
    const { watching } = z.object({ watching: z.boolean() }).parse(req.body);
    res.json({ bug: await bugs.setWatching(numberOf(req), watching, bugActorOf(res)) });
  }),
);
bugTrackerRouter.post(
  '/bugs/:number/links',
  asyncHandler(async (req: Request, res: Response) => {
    const { to } = z.object({ to: z.union([z.number().int().positive(), z.string().max(20)]) }).parse(req.body);
    const toNumber = typeof to === 'number' ? to : bugNumberFrom(to);
    if (toNumber === null) throw new BadRequestError('Enter a bug number, like BUG-12.', 'BAD_BUG_NUMBER');
    res.status(201).json({ bug: await bugs.linkRelated(numberOf(req), toNumber, bugActorOf(res)) });
  }),
);
bugTrackerRouter.delete(
  '/bugs/:number/links/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await bugs.unlink(numberOf(req), idParam.parse(req.params).id, bugActorOf(res)) });
  }),
);

bugTrackerRouter.patch(
  '/comments/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await bugs.editComment(idParam.parse(req.params).id, editCommentSchema.parse(req.body), bugActorOf(res)) });
  }),
);
bugTrackerRouter.delete(
  '/comments/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ bug: await bugs.deleteComment(idParam.parse(req.params).id, bugActorOf(res)) });
  }),
);

// A file is the request body (as /api/uploads/direct and the blog's images):
// read raw, capped at the door, and its type taken from its bytes. It is
// attached when the report or comment that names its id is sent.
bugTrackerRouter.post(
  '/files',
  express.raw({ type: () => true, limit: BUG_LIMITS.fileBytes + 1024 }),
  asyncHandler(async (req: Request, res: Response) => {
    const { filename } = z.object({ filename: z.string().trim().max(200).default('file') }).parse(req.query);
    const body = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
    res.status(201).json({ file: await files.presentFile(await files.uploadFile({ body, filename }, bugActorOf(res))) });
  }),
);
bugTrackerRouter.delete(
  '/files/:id',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await bugs.deleteFile(idParam.parse(req.params).id, bugActorOf(res)));
  }),
);

// ── Team (super admin) ─────────────────────────────────────────────────────

const teamRouter = Router();
teamRouter.use(requireSuperAdmin);

teamRouter.get(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const f = z.object({ q: z.string().trim().max(100).optional(), status: z.enum(['INVITED', 'ACTIVE', 'DEACTIVATED']).optional(), role: role.optional() }).parse(req.query);
    res.json(await team.listMembers(f));
  }),
);
teamRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ name: text('Name', 2, 120), email, phone: phone.optional(), role }).parse(req.body);
    res.status(201).json(await team.createMember(input, bugActorOf(res)));
  }),
);
teamRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z
      .object({ name: text('Name', 2, 120), email, phone, role })
      .partial()
      .refine((v) => Object.keys(v).length > 0, 'Nothing to update')
      .parse(req.body);
    res.json({ member: await team.updateMember(idParam.parse(req.params).id, input) });
  }),
);
teamRouter.post(
  '/:id/send-link',
  asyncHandler(async (req: Request, res: Response) => {
    res.json(await team.sendPasswordLink(idParam.parse(req.params).id, bugActorOf(res)));
  }),
);
teamRouter.post(
  '/:id/deactivate',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ member: await team.deactivateMember(idParam.parse(req.params).id) });
  }),
);
teamRouter.post(
  '/:id/reactivate',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ member: await team.reactivateMember(idParam.parse(req.params).id) });
  }),
);
teamRouter.post(
  '/:id/sign-out',
  asyncHandler(async (req: Request, res: Response) => {
    res.json({ member: await team.signOutEverywhere(idParam.parse(req.params).id) });
  }),
);
bugTrackerRouter.use('/team', teamRouter);

// ── Modules (super admin) ──────────────────────────────────────────────────

const moduleName = text('Module name', modules.MODULE_NAME.min, modules.MODULE_NAME.max);
const developerId = z.union([z.string().uuid('Choose a developer'), z.null()]);

const modulesRouter = Router();
modulesRouter.use(requireSuperAdmin);

modulesRouter.get(
  '/',
  asyncHandler(async (_req: Request, res: Response) => {
    res.json({ modules: await modules.listModules({ includeArchived: true }) });
  }),
);
modulesRouter.post(
  '/',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z.object({ name: moduleName, defaultDeveloperId: developerId.optional() }).parse(req.body);
    res.status(201).json({ module: await modules.createModule(input) });
  }),
);
modulesRouter.put(
  '/order',
  asyncHandler(async (req: Request, res: Response) => {
    const { ids } = z.object({ ids: z.array(z.string().uuid()).min(1).max(200) }).parse(req.body);
    res.json({ modules: await modules.reorderModules(ids) });
  }),
);
modulesRouter.patch(
  '/:id',
  asyncHandler(async (req: Request, res: Response) => {
    const input = z
      .object({ name: moduleName, defaultDeveloperId: developerId, archived: z.boolean() })
      .partial()
      .refine((v) => Object.keys(v).length > 0, 'Nothing to update')
      .parse(req.body);
    res.json({ module: await modules.updateModule(idParam.parse(req.params).id, input) });
  }),
);
bugTrackerRouter.use('/modules', modulesRouter);
