import { z } from 'zod';

export const approvalActionSchema = z.object({
  action: z.enum(['APPROVE', 'REJECT']),
  comments: z.string().optional(),
  rejectionReason: z.string().optional(),
});

// Helper to validate UUID or requestNumber format
// Supports both old format (REQ-YYYY-NNNNN) and new format (REQ-YYYY-MM-XXXX)
const workflowIdValidator = z.string().refine(
  (val) => {
    // Check if it's a UUID
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    if (uuidRegex.test(val)) {
      return true;
    }
    // Check if it's a valid requestNumber format
    // Old format: REQ-YYYY-NNNNN (e.g., REQ-2025-12057) - 5+ digits after year
    // New format: REQ-YYYY-MM-XXXX (e.g., REQ-2025-11-0001) - 2-digit month, 4-digit counter
    const oldFormatRegex = /^REQ-\d{4}-\d{5,}$/i; // Old: REQ-2025-12057
    const newFormatRegex = /^REQ-\d{4}-\d{2}-\d{4}$/i; // New: REQ-2025-11-0001
    if (oldFormatRegex.test(val) || newFormatRegex.test(val)) {
      return true;
    }
    return false;
  },
  {
    message: 'Invalid workflow ID - must be a UUID or requestNumber format (e.g., REQ-2025-11-0001 or REQ-2025-12057)'
  }
);

export const approvalParamsSchema = z.object({
  id: workflowIdValidator,
  levelId: z.string().uuid('Invalid approval level ID'),
});

export const validateApprovalAction = (data: any) => {
  return approvalActionSchema.parse(data);
};
