import { Router, Request, Response } from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { env } from '../../config/env';
import { asyncHandler } from '../../middleware/asyncHandler';
import { applyStatus, saveInbound, WaContact, WaInbound, WaStatus } from './whatsapp-inbox.service';

/**
 * The Meta WhatsApp Cloud API webhook (12 Oct 2026):
 *   https://<api host>/api/webhooks/whatsapp
 *
 * GET  — Meta's one-time check when the URL is saved: echo hub.challenge if
 *        hub.verify_token matches WHATSAPP_VERIFY_TOKEN.
 * POST — events, signed with the app secret (X-Hub-Signature-256 over the
 *        raw body). Unsigned or mis-signed calls get 401 and change nothing.
 *
 * Mounted under /api/webhooks, which reads bodies raw. No session, no tenant:
 * the signature is the credential. Every signed call gets a 200 even if one
 * item in it fails, or Meta would keep resending the whole batch.
 */

export const whatsappWebhookRouter = 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);
};

whatsappWebhookRouter.get('/whatsapp', (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.WHATSAPP_VERIFY_TOKEN && same(token, env.WHATSAPP_VERIFY_TOKEN)) {
    res.status(200).type('text/plain').send(challenge);
    return;
  }
  res.sendStatus(403);
});

interface WaChange {
  field?: string;
  value?: {
    metadata?: { phone_number_id?: string };
    contacts?: WaContact[];
    messages?: WaInbound[];
    statuses?: WaStatus[];
  };
}

whatsappWebhookRouter.post(
  '/whatsapp',
  asyncHandler(async (req: Request, res: Response) => {
    if (!env.WHATSAPP_APP_SECRET) {
      res.status(503).json({ error: 'WhatsApp 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', env.WHATSAPP_APP_SECRET).update(raw).digest('hex')}`;
    if (!same(given, expected)) {
      res.status(401).json({ error: 'Bad signature' });
      return;
    }
    let body: { object?: string; entry?: { changes?: WaChange[] }[] };
    try {
      body = JSON.parse(raw.toString('utf8'));
    } catch {
      res.status(400).json({ error: 'Bad JSON' });
      return;
    }
    for (const entry of body.entry ?? []) {
      for (const change of entry.changes ?? []) {
        const v = change.value;
        if (change.field !== 'messages' || !v) continue;
        // Other numbers on the same Meta app are not ours to record.
        if (env.WHATSAPP_PHONE_NUMBER_ID && v.metadata?.phone_number_id && v.metadata.phone_number_id !== env.WHATSAPP_PHONE_NUMBER_ID) continue;
        for (const s of v.statuses ?? []) await safely(() => applyStatus(s));
        for (const m of v.messages ?? []) await safely(() => saveInbound(m, v.contacts));
      }
    }
    res.sendStatus(200);
  }),
);

async function safely(fn: () => Promise<void>) {
  try {
    await fn();
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error('[whatsapp] webhook item failed:', err instanceof Error ? err.message : err);
  }
}
