import { Router, Request, Response, NextFunction } from 'express';

/**
 * HTTPS front door to the n8n booking pass-through webhook.
 * Sarvam requires https://; n8n itself may only listen on HTTP.
 *
 * POST /v1/integrations/n8n/book-slot
 * → forwards body to N8N_BOOK_SLOT_WEBHOOK_URL (or default local n8n webhook)
 * → returns calendar JSON unchanged (created / availableTimes)
 */
const router = Router();

const DEFAULT_N8N_WEBHOOK =
  process.env.N8N_BOOK_SLOT_WEBHOOK_URL?.trim() ||
  'http://127.0.0.1:5678/webhook/calendar-book-slot';

router.post('/book-slot', async (req: Request, res: Response, next: NextFunction) => {
  try {
    const upstream = await fetch(DEFAULT_N8N_WEBHOOK, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
      body: JSON.stringify(req.body ?? {}),
      signal: AbortSignal.timeout(25_000),
    });

    const text = await upstream.text();
    const contentType = upstream.headers.get('content-type') || 'application/json';
    res.status(upstream.status).setHeader('Content-Type', contentType);

    if (contentType.includes('application/json')) {
      try {
        res.json(JSON.parse(text));
        return;
      } catch {
        /* fall through */
      }
    }
    res.send(text);
  } catch (err) {
    next(err);
  }
});

export default router;
