/**
 * CPC-CSD permission middleware – enforces API-driven viewer list.
 * Use after authenticateToken so req.user is available.
 */

import { Request, Response, NextFunction } from 'express';
import { ResponseHandler } from '../utils/responseHandler';
import { canAccessCpcCdc } from '../services/cpcPermission.service';

export const requireCpcCdcAccess = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<void> => {
  try {
    const user = req.user;
    if (!user?.userId || !user?.email) {
      ResponseHandler.unauthorized(res, 'Authentication required');
      return;
    }

    const role = (user as any).role as string | undefined;
    const allowed = await canAccessCpcCdc(user.email, role);
    if (!allowed) {
      ResponseHandler.forbidden(res, 'You do not have permission to access CPC-CSD');
      return;
    }

    next();
  } catch (error) {
    ResponseHandler.error(res, 'Permission check failed', 500, error instanceof Error ? error.message : 'Unknown error');
  }
};

