import { Request, Response } from 'express';
import { z } from 'zod';

import { getErrorMessage } from '../../../utils/error-utils';
import { AccessSummaryFiltersDto, UserActivityFiltersDto, SecurityEventsFiltersDto } from '../governance.dto';

import { reportingService } from './reporting.service';

/**
 * EN: Reporting Controller
 * VI: Controller báo cáo
 */
export class ReportingController {
  /**
   * EN: Get access summary
   * VI: Lấy tổng quan truy cập
   */
  async accessSummary(req: Request, res: Response): Promise<void> {
    try {
      const filters = AccessSummaryFiltersDto.parse({
        periodStart: req.query.periodStart as string,
        periodEnd: req.query.periodEnd as string,
        organizationId: req.query.organizationId as string,
      });

      const summary = await reportingService.getAccessSummary(filters);

      res.json({
        success: true,
        data: summary,
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid filters',
            details: error.issues,
          },
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'GET_ACCESS_SUMMARY_FAILED',
          message: getErrorMessage(error) || 'Failed to get access summary',
        },
      });
    }
  }

  /**
   * EN: Get user activity
   * VI: Lấy hoạt động của user
   */
  async userActivity(req: Request, res: Response): Promise<void> {
    try {
      const filters = UserActivityFiltersDto.parse({
        userId: req.params.userId || req.query.userId as string,
        periodStart: req.query.periodStart as string,
        periodEnd: req.query.periodEnd as string,
        eventType: req.query.eventType as string,
      });

      const activity = await reportingService.getUserActivity(filters);

      res.json({
        success: true,
        data: activity,
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid filters',
            details: error.issues,
          },
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'GET_USER_ACTIVITY_FAILED',
          message: getErrorMessage(error) || 'Failed to get user activity',
        },
      });
    }
  }

  /**
   * EN: Get security events
   * VI: Lấy các sự kiện bảo mật
   */
  async securityEvents(req: Request, res: Response): Promise<void> {
    try {
      const filters = SecurityEventsFiltersDto.parse({
        periodStart: req.query.periodStart as string,
        periodEnd: req.query.periodEnd as string,
        eventType: req.query.eventType as string,
        success: req.query.success === 'true' ? true : req.query.success === 'false' ? false : undefined,
        skip: parseInt(req.query.skip as string) || 0,
        take: parseInt(req.query.take as string) || 20,
      });

      const result = await reportingService.getSecurityEvents(filters);

      res.json({
        success: true,
        data: {
          events: result.events,
          pagination: {
            total: result.total,
            skip: filters.skip,
            take: filters.take,
          },
        },
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid filters',
            details: error.issues,
          },
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'GET_SECURITY_EVENTS_FAILED',
          message: getErrorMessage(error) || 'Failed to get security events',
        },
      });
    }
  }

  /**
   * EN: Get compliance status
   * VI: Lấy trạng thái tuân thủ
   */
  async complianceStatus(req: Request, res: Response): Promise<void> {
    try {
      const status = await reportingService.getComplianceStatus();

      res.json({
        success: true,
        data: status,
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'GET_COMPLIANCE_STATUS_FAILED',
          message: getErrorMessage(error) || 'Failed to get compliance status',
        },
      });
    }
  }

  /**
   * EN: Get risk overview
   * VI: Lấy tổng quan rủi ro
   */
  async riskOverview(req: Request, res: Response): Promise<void> {
    try {
      const overview = await reportingService.getRiskOverview();

      res.json({
        success: true,
        data: overview,
      });
    } catch (error: unknown) {
      res.status(500).json({
        success: false,
        error: {
          code: 'GET_RISK_OVERVIEW_FAILED',
          message: getErrorMessage(error) || 'Failed to get risk overview',
        },
      });
    }
  }
}

export const reportingController = new ReportingController();
