import { Response } from 'express';
import { pauseService } from '@services/pause.service';
import { ResponseHandler } from '@utils/responseHandler';
import type { AuthenticatedRequest } from '../types/express';
import { z } from 'zod';

// Validation schemas
const pauseWorkflowSchema = z.object({
  levelId: z.string().uuid().optional().nullable(),
  reason: z.string().min(1, 'Reason is required').max(1000, 'Reason must be less than 1000 characters'),
  resumeDate: z.string().datetime().or(z.date())
});

const resumeWorkflowSchema = z.object({
  notes: z.string().max(1000, 'Notes must be less than 1000 characters').optional()
});

export class PauseController {
  /**
   * Pause a workflow
   * POST /workflows/:id/pause
   */
  async pauseWorkflow(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const userId = req.user?.userId;

      if (!userId) {
        ResponseHandler.error(res, 'Unauthorized', 401);
        return;
      }

      // Validate request body
      const validated = pauseWorkflowSchema.parse(req.body);
      const resumeDate = validated.resumeDate instanceof Date 
        ? validated.resumeDate 
        : new Date(validated.resumeDate);

      const result = await pauseService.pauseWorkflow(
        id,
        validated.levelId || null,
        userId,
        validated.reason,
        resumeDate
      );

      ResponseHandler.success(res, {
        workflow: result.workflow,
        level: result.level
      }, 'Workflow paused successfully', 200);
    } catch (error: any) {
      if (error instanceof z.ZodError) {
        ResponseHandler.error(res, 'Validation failed', 400, error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join('; '));
        return;
      }
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to pause workflow', 400, errorMessage);
    }
  }

  /**
   * Resume a paused workflow
   * POST /workflows/:id/resume
   */
  async resumeWorkflow(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const userId = req.user?.userId;

      if (!userId) {
        ResponseHandler.error(res, 'Unauthorized', 401);
        return;
      }

      // Validate request body (notes is optional)
      const validated = resumeWorkflowSchema.parse(req.body || {});

      const result = await pauseService.resumeWorkflow(id, userId, validated.notes);

      ResponseHandler.success(res, {
        workflow: result.workflow,
        level: result.level
      }, 'Workflow resumed successfully', 200);
    } catch (error: any) {
      if (error instanceof z.ZodError) {
        ResponseHandler.error(res, 'Validation failed', 400, error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join('; '));
        return;
      }
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to resume workflow', 400, errorMessage);
    }
  }

  /**
   * Retrigger pause (initiator requests approver to resume)
   * POST /workflows/:id/pause/retrigger
   */
  async retriggerPause(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const userId = req.user?.userId;

      if (!userId) {
        ResponseHandler.error(res, 'Unauthorized', 401);
        return;
      }

      await pauseService.retriggerPause(id, userId);

      ResponseHandler.success(res, null, 'Pause retrigger request sent successfully', 200);
    } catch (error: any) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to retrigger pause', 400, errorMessage);
    }
  }

  /**
   * Get pause details for a workflow
   * GET /workflows/:id/pause
   */
  async getPauseDetails(req: AuthenticatedRequest, res: Response): Promise<void> {
    try {
      const { id } = req.params;

      const pauseDetails = await pauseService.getPauseDetails(id);

      if (!pauseDetails) {
        ResponseHandler.success(res, { isPaused: false }, 'Workflow is not paused', 200);
        return;
      }

      ResponseHandler.success(res, pauseDetails, 'Pause details retrieved successfully', 200);
    } catch (error: any) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      ResponseHandler.error(res, 'Failed to get pause details', 400, errorMessage);
    }
  }
}

export const pauseController = new PauseController();

