import { Response, NextFunction } from 'express';
import { AuthenticatedRequest } from '../../../shared/types/index.js';
import { featureFlagsService } from '../services/feature-flags.instance.js';

export const featureFlagsMiddleware = async (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
  // Solo evaluamos si hay tenant (request autenticado)
  if (!req.user || !req.user.tenantId) {
    return next();
  }

  try {
    // Inyectamos un objeto helper en el request para chequear flags facilmente en controladores/servicios
    (req as any).flags = {
      isEnabled: async (code: string) => featureFlagsService.isEnabled(code, req.user!.tenantId),
      evaluate: async (code: string) => featureFlagsService.evaluateFlag(code, req.user!.tenantId),
      evaluateMany: async (codes: string[]) => featureFlagsService.evaluateFlags(codes, req.user!.tenantId)
    };
  } catch (err) {
    console.error('Feature flags middleware error', err);
  }

  next();
};
