import type { Request, Response } from 'express';
import {
  extractApiKey,
  isProductionSecurityMode,
  loadCustomerSecurityPolicy,
  principalHasScope,
  resolveOmnlPrincipal,
} from '@dbis/integration-foundation';
import { loadExchangeConfig } from '../config';

export function apiKey(req: Request): string | undefined {
  return extractApiKey(req);
}

export function requireScope(req: Request, res: Response, scope: string): boolean {
  const cfg = loadExchangeConfig();
  if (!cfg.production.requireApiKey && !isProductionSecurityMode()) return true;

  const policy = loadCustomerSecurityPolicy();
  if (policy.requireApiKeyAllExchangeRoutes || cfg.production.requireApiKey) {
    const principal = resolveOmnlPrincipal(req);
    if (!principal) {
      res.status(401).json({ error: 'Unauthorized', hint: 'Valid customer or super-admin API key required' });
      return false;
    }
    if (!principalHasScope(principal, scope)) {
      res.status(403).json({ error: 'Forbidden', scope, role: principal.role });
      return false;
    }
    return true;
  }
  return true;
}

export function requireSuperAdmin(req: Request, res: Response): boolean {
  return requireScope(req, res, 'admin');
}

export function requireRead(req: Request, res: Response): boolean {
  return requireScope(req, res, 'read');
}

export function requireTrade(req: Request, res: Response): boolean {
  return requireScope(req, res, 'trade');
}
