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

import { NotFoundError } from '../../../errors/http-error';
import { getErrorMessage } from '../../../utils/error-utils';
import { CreatePolicyTemplateDto, TestPolicyDto } from '../governance.dto';

import { policyGovernanceService } from './policy-governance.service';

/**
 * EN: Policy Governance Controller
 * VI: Controller quản trị policy
 */
export class PolicyGovernanceController {
  /**
   * EN: Get templates
   * VI: Lấy các template
   */
  async getTemplates(req: Request, res: Response): Promise<void> {
    try {
      const category = req.query.category as any;
      const templates = await policyGovernanceService.getTemplates(category);

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

  /**
   * EN: Create template
   * VI: Tạo template
   */
  async createTemplate(req: Request, res: Response): Promise<void> {
    try {
      const data = CreatePolicyTemplateDto.parse(req.body);
      const template = await policyGovernanceService.createTemplate(data, req);

      res.status(201).json({
        success: true,
        data: template,
        message: 'Policy template created successfully / Template policy đã được tạo thành công',
      });
    } catch (error: unknown) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'Invalid input',
            details: error.issues,
          },
        });
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'CREATE_TEMPLATE_FAILED',
          message: getErrorMessage(error) || 'Failed to create template',
        },
      });
    }
  }

  /**
   * EN: Get policy versions
   * VI: Lấy các phiên bản policy
   */
  async getVersions(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const versions = await policyGovernanceService.getPolicyVersions(id);

      res.json({
        success: true,
        data: versions,
      });
    } catch (error: unknown) {
      if (error instanceof NotFoundError) {
        res.status(404).json(error.toApiResponse());
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'GET_VERSIONS_FAILED',
          message: getErrorMessage(error) || 'Failed to get policy versions',
        },
      });
    }
  }

  /**
   * EN: Test policy
   * VI: Test policy
   */
  async test(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const data = TestPolicyDto.parse(req.body);
      const result = await policyGovernanceService.testPolicy(id, data.testData, req);

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

      if (error instanceof NotFoundError) {
        res.status(404).json(error.toApiResponse());
        return;
      }

      res.status(500).json({
        success: false,
        error: {
          code: 'TEST_POLICY_FAILED',
          message: getErrorMessage(error) || 'Failed to test policy',
        },
      });
    }
  }
}

export const policyGovernanceController = new PolicyGovernanceController();
