import { NextFunction, Request, Response } from 'express';
import db from '../../config/database';
import { SLAGovernanceService } from '../../domains/Billing/SLAGovernanceService';
import { logger } from '../../utils/logger';

/**
 * [CORE_TOB_06] SLA 熔断中间件
 * @description 在请求进入前检查租户状态，请求结束后记录指标
 */
export async function slaGuard(req: Request, res: Response, next: NextFunction) {
  // 公开路由白名单
  const PUBLIC_ROUTES = ['/api/v1/auth/login', '/health'];
  if (PUBLIC_ROUTES.includes(req.path)) {
    return next();
  }

  const context = (req as any).traceContext;
  if (!context || !context.tenantId) return next();

  const tenantId = context.tenantId;

  // 1. 检查租户是否被熔断 (SUSPENDED)
  const tenant = await db('cf_tenants').where({ id: tenantId }).first();
  if (tenant && tenant.status === 'SUSPENDED') {
    logger.warn(`[SLA] Request blocked for suspended tenant: ${tenantId}`);
    return res.status(429).json({
      success: false,
      error: 'Tenant SLA breach: Service temporarily suspended. Please contact support.'
    });
  }

  // 2. 拦截响应以记录指标
  const originalJson = res.json;
  res.json = function(data: any) {
    const success = res.statusCode >= 200 && res.statusCode < 300;
    SLAGovernanceService.recordMetric(tenantId, success).catch(err => 
      logger.error(`[SLA] Failed to record metric: ${err.message}`)
    );
    return originalJson.call(this, data);
  };

  next();
}
