'use client'

import { useMutation, useQueryClient } from '@tanstack/react-query'
import { apiPatch } from '@/lib/api/client'
import { orderKeys } from './use-orders'

// Types
export interface AutomationChangeResponse {
  success: boolean
  message: string
  order: {
    id: string
    automationMode: string
    automationPausedAt: string | null
    automationPausedReason: string | null
  }
}

export type AutomationAction = 'auto' | 'manual' | 'pause' | 'resume'

// API call
async function changeAutomationMode(
  orderId: string,
  action: AutomationAction
): Promise<AutomationChangeResponse> {
  return apiPatch<AutomationChangeResponse>(
    `/api/v1/admin/orders/${orderId}/automation`,
    { action }
  )
}

// Hook
export function useChangeAutomationMode() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ orderId, action }: { orderId: string; action: AutomationAction }) =>
      changeAutomationMode(orderId, action),
    onSuccess: (_, { orderId }) => {
      // Invalidate order to get updated automation state
      queryClient.invalidateQueries({ queryKey: orderKeys.detail(orderId) })
    },
  })
}
