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

class CpcPermissionController {
  /**
   * GET /api/v1/cpc-csd/permissions (legacy: /api/v1/cpc-cdc/permissions)
   * Returns CPC-CSD access permission for current user.
   */
  async getPermissions(req: Request, res: Response): 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 canViewCpcCsd = await canAccessCpcCdc(user.email, role);

      ResponseHandler.success(
        res,
        { canViewCpcCsd, canViewCpcCdc: canViewCpcCsd },
        'CPC-CSD permissions'
      );
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[CpcPermissionController] getPermissions error:', error);
      ResponseHandler.error(res, 'Failed to get CPC-CSD permissions', 500, errorMessage);
    }
  }
}

export const cpcPermissionController = new CpcPermissionController();

