import { Request, Response } from 'express';
import { ApprovalService } from '@services/approval.service';
import { validateApprovalAction } from '@validators/approval.validator';
import { ResponseHandler } from '@utils/responseHandler';
import type { AuthenticatedRequest } from '../types/express';
import { getRequestMetadata } from '@utils/requestUtils';

const approvalService = new ApprovalService();

export class ApprovalController {
  async approveLevel(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { levelId } = req.params;
      const validatedData = validateApprovalAction(req.body);
      
      const requestMeta = getRequestMetadata(req);
      const level = await approvalService.approveLevel(levelId, validatedData, req.user.userId, {
        ipAddress: requestMeta.ipAddress,
        userAgent: requestMeta.userAgent
      });
      
      if (!level) {
        ResponseHandler.notFound(res, 'Approval level not found');
        return;
      }

      ResponseHandler.success(res, level, 'Approval level updated successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to update approval level', 400, errorMessage);
    }
  }

  async getCurrentApprovalLevel(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const level = await approvalService.getCurrentApprovalLevel(id);
      
      ResponseHandler.success(res, level, 'Current approval level retrieved successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to get current approval level', 500, errorMessage);
    }
  }

  async getApprovalLevels(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const levels = await approvalService.getApprovalLevels(id);
      
      ResponseHandler.success(res, levels, 'Approval levels retrieved successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to get approval levels', 500, errorMessage);
    }
  }
}
