/**
 * Workflow hooks
 * React Query hooks for workflow operations
 */
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { workflowService } from '../services/workflowService';
import {
  CreateWorkflowDto,
  UpdateWorkflowItemDto,
  ApprovalRequestDto,
} from '../types/workflow.types';
import { PaginationParams } from '@/shared/types/api.types';
import { toast } from 'sonner';

/**
 * Get all workflows with pagination
 */
export const useWorkflows = (params?: PaginationParams & { project_name?: string }) => {
  return useQuery({
    queryKey: ['workflows', params],
    queryFn: () => workflowService.getAll(params),
    staleTime: 30000, // 30 seconds
  });
};

/**
 * Get a single workflow by ID
 */
export const useWorkflow = (id: string | undefined) => {
  return useQuery({
    queryKey: ['workflow', id],
    queryFn: () => workflowService.getById(id!),
    enabled: !!id,
    staleTime: 30000,
  });
};

/**
 * Create a new workflow
 */
export const useCreateWorkflow = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateWorkflowDto) => workflowService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['workflows'] });
      toast.success('Workflow created successfully');
    },
    onError: (error: any) => {
      toast.error(error.message || 'Failed to create workflow');
    },
  });
};

/**
 * Update a workflow item
 */
export const useUpdateWorkflowItem = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      workflowId,
      data,
    }: {
      workflowId: string;
      data: UpdateWorkflowItemDto;
    }) => workflowService.updateItem(workflowId, data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['workflow', variables.workflowId] });
      queryClient.invalidateQueries({ queryKey: ['workflows'] });
      toast.success('Workflow item updated');
    },
    onError: (error: any) => {
      toast.error(error.message || 'Failed to update workflow item');
    },
  });
};

/**
 * Submit an approval
 */
export const useSubmitApproval = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({
      workflowId,
      data,
    }: {
      workflowId: string;
      data: ApprovalRequestDto;
    }) => workflowService.submitApproval(workflowId, data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ['workflow', variables.workflowId] });
      queryClient.invalidateQueries({ queryKey: ['workflows'] });
      toast.success('Approval submitted');
    },
    onError: (error: any) => {
      toast.error(error.message || 'Failed to submit approval');
    },
  });
};

/**
 * Advance workflow phase
 */
export const useAdvanceWorkflow = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (workflowId: string) => workflowService.advancePhase(workflowId),
    onSuccess: (_, workflowId) => {
      queryClient.invalidateQueries({ queryKey: ['workflow', workflowId] });
      queryClient.invalidateQueries({ queryKey: ['workflows'] });
      toast.success('Workflow advanced to next phase');
    },
    onError: (error: any) => {
      toast.error(error.message || 'Failed to advance workflow');
    },
  });
};

/**
 * Delete a workflow
 */
export const useDeleteWorkflow = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => workflowService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['workflows'] });
      toast.success('Workflow deleted');
    },
    onError: (error: any) => {
      toast.error(error.message || 'Failed to delete workflow');
    },
  });
};
