import { Router, Request, Response } from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { env } from '../../config/env';
import { asyncHandler } from '../../middleware/asyncHandler';
import { processMetaLead, recordMetaLeads, type MetaLeadEvent } from './crm-touch.service';

/**
 * Meta lead ads (Sprint L4): the Page webhook for the "leadgen" field.
 *   https://<api host>/api/webhooks/meta-leads
 *
 * GET  — Meta's check when the URL is saved: echo hub.challenge when
 *        hub.verify_token matches META_LEADS_VERIFY_TOKEN.
 * POST — signed with the app secret (X-Hub-Signature-256 over the raw body;
 *        META_APP_SECRET, or WHATSAPP_APP_SECRET when it is the same app).
 *        Each lead id is kept once and answered with 200 at once; its answers
 *        are fetched right after, and the CRM clock retries any that fail.
 *
 * Mounted under /api/webhooks, which reads bodies raw. No session: the
 * signature is the credential.
 */

export const metaLeadsWebhookRouter = Router();

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

metaLeadsWebhookRouter.get('/meta-leads', (req: Request, res: Response) => {
  const mode = String(req.query['hub.mode'] ?? '');
  const token = String(req.query['hub.verify_token'] ?? '');
  const challenge = String(req.query['hub.challenge'] ?? '');
  if (mode === 'subscribe' && env.META_LEADS_VERIFY_TOKEN && same(token, env.META_LEADS_VERIFY_TOKEN)) {
    res.status(200).type('text/plain').send(challenge);
    return;
  }
  res.sendStatus(403);
});

metaLeadsWebhookRouter.post(
  '/meta-leads',
  asyncHandler(async (req: Request, res: Response) => {
    const secret = env.META_APP_SECRET ?? env.WHATSAPP_APP_SECRET;
    if (!secret) {
      res.status(503).json({ error: 'Meta lead webhook is not configured' });
      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', secret).update(raw).digest('hex')}`;
    if (!same(given, expected)) {
      res.status(401).json({ error: 'Bad signature' });
      return;
    }
    let body: { object?: string; entry?: { changes?: { field?: string; value?: MetaLeadEvent }[] }[] };
    try {
      body = JSON.parse(raw.toString('utf8'));
    } catch {
      res.status(400).json({ error: 'Bad JSON' });
      return;
    }
    const events = (body.entry ?? []).flatMap((e) => (e.changes ?? []).filter((c) => c.field === 'leadgen' && c.value).map((c) => c.value!));
    const ids = await recordMetaLeads(events);
    res.sendStatus(200);
    // After the answer: Meta wants its 200 fast, and fetching a lead takes a round trip.
    for (const id of ids) {
      processMetaLead(id).catch((err) => {
        // eslint-disable-next-line no-console
        console.error(`[meta-leads] ${id} failed: ${err instanceof Error ? err.message : String(err)}`);
      });
    }
  }),
);
