import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
import { Router, type Request, type Response } from 'express';
import { asyncHandler } from '../../middleware/asyncHandler';
import { rateLimit } from '../../middleware/rateLimit';
import { env } from '../../config/env';
import { handleGithub } from './bug-github.service';

/**
 * GitHub's webhook for the bug tracker (docs/bug-tracker-plan.md, BT6):
 *
 *   POST /api/webhooks/github
 *
 * No sign-in: the signature is the credential. GitHub signs the raw body with
 * the secret typed into the repository's webhook (X-Hub-Signature-256); a
 * request without a matching signature is refused before anything is read.
 * Mounted with the other webhooks, before the JSON parser, so the body is raw.
 */
export const githubWebhookRouter = Router();

const limiter = rateLimit({ windowMs: 60 * 1000, max: 240, name: 'bug-github-webhook' });

function same(a: string, b: string): boolean {
  const x = Buffer.from(a);
  const y = Buffer.from(b);
  return x.length === y.length && timingSafeEqual(x, y);
}

githubWebhookRouter.post(
  '/github',
  limiter,
  asyncHandler(async (req: Request, res: Response) => {
    if (!env.BUG_GITHUB_WEBHOOK_SECRET) {
      res.status(503).json({ error: 'The GitHub webhook is not set up on this server' });
      return;
    }
    const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
    const given = String(req.headers['x-hub-signature-256'] ?? '');
    const expected = `sha256=${createHmac('sha256', env.BUG_GITHUB_WEBHOOK_SECRET).update(raw).digest('hex')}`;
    if (!same(given, expected)) {
      res.status(401).json({ error: 'Bad signature' });
      return;
    }
    let body: unknown;
    try {
      body = JSON.parse(raw.toString('utf8'));
    } catch {
      res.status(400).json({ error: 'Send JSON: set the webhook’s content type to application/json' });
      return;
    }
    const event = String(req.headers['x-github-event'] ?? '').slice(0, 40);
    const header = String(req.headers['x-github-delivery'] ?? '');
    // GitHub always sends a delivery id; without one, the body's hash stands in, so a repeat is still a repeat.
    const delivery = /^[\w-]{8,80}$/.test(header) ? header : createHash('sha256').update(raw).digest('hex');
    res.json(await handleGithub(event, delivery, body));
  }),
);
