import { NextFunction, Request, Response } from 'express';
import { AuthService } from '../../services/AuthService';

const REQUIRED_HEADERS = [
  'x-tenant-id',
  'x-trace-id',
] as const;

/**
 * [CORE_GOV_05] 运行时强门禁: 租户上下文与身份验证
 * @description 优先从 JWT 提取上下文，否则从 Header 提取 (仅限系统/节点调用)
 */
export function requireTraceContext(req: Request, res: Response, next: NextFunction) {
  // 公开路由白名单
  const PUBLIC_ROUTES = ['/api/v1/auth/login', '/health'];
  if (PUBLIC_ROUTES.includes(req.path)) {
    return next();
  }

  let context: any = null;

  // 1. 尝试从 Authorization: Bearer <Token> 提取 JWT
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    const token = authHeader.substring(7);
    const payload = AuthService.verifyToken(token);
    if (payload) {
      context = {
        tenantId: payload.tenantId,
        shopId: payload.shopId,
        userId: payload.userId,
        roleCode: payload.role,
        taskId: String(req.headers['x-task-id'] || ''),
        traceId: String(req.headers['x-trace-id'] || `trace-${Date.now()}`),
        source: 'jwt'
      };
    } else {
      return res.status(401).json({ success: false, error: 'Invalid or expired authentication token' });
    }
  }

  // 2. 如果没有 JWT，检查 Header 门禁 (适用于 Node Agent / Extension 快速调用)
  if (!context) {
    const missing = REQUIRED_HEADERS.filter((header) => {
      const value = req.headers[header];
      return typeof value !== 'string' || value.trim().length === 0;
    });

    if (missing.length > 0) {
      return res.status(400).json({
        success: false,
        error: `Missing required trace context headers: ${missing.join(', ')}`,
      });
    }

    context = {
      tenantId: String(req.headers['x-tenant-id']),
      shopId: String(req.headers['x-shop-id'] || ''),
      taskId: String(req.headers['x-task-id'] || ''),
      traceId: String(req.headers['x-trace-id']),
      userId: String(req.headers['x-user-id'] || 'system'),
      roleCode: String(req.headers['x-role-code'] || 'UNKNOWN'),
      source: 'header'
    };
  }

  // 3. 挂载上下文
  (req as any).traceContext = context;

  next();
}

/**
 * [CORE_AUTH_01] 仅限管理员或特定角色访问的门禁
 */
export function authorize(roles: string[]) {
  return (req: Request, res: Response, next: NextFunction) => {
    const context = (req as any).traceContext;
    if (!context || !roles.includes(context.roleCode)) {
      return res.status(403).json({ success: false, error: 'Forbidden: Insufficient permissions' });
    }
    next();
  };
}

