import type { Request, Response, NextFunction } from 'express';
import { deriveIdempotencyKey, IdempotencyStore } from '@dbis/integration-foundation';

const store = new IdempotencyStore();

const IDEMPOTENT_PATHS = ['/omnl/iso20022/messages'];

/**
 * Dedup financial POSTs when X-Idempotency-Key header is present.
 */
export function omnlIdempotencyMiddleware(req: Request, res: Response, next: NextFunction): void {
  if (req.method !== 'POST') {
    next();
    return;
  }
  const path = req.path.replace(/^\/api\/v1/, '');
  if (!IDEMPOTENT_PATHS.some((p) => path.endsWith(p))) {
    next();
    return;
  }

  const headerKey = String(req.headers['x-idempotency-key'] ?? '').trim();
  if (!headerKey) {
    next();
    return;
  }

  const key = deriveIdempotencyKey({
    tenantId: String(req.headers['x-tenant-id'] ?? 'omnl'),
    entityId: String(req.headers['x-entity-id'] ?? 'default'),
    operation: path,
    resourceId: headerKey,
  });

  if (!store.record(key)) {
    res.status(409).json({ error: 'duplicate_idempotency_key', idempotencyKey: headerKey });
    return;
  }

  next();
}
