'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../client'
import { useAuthReady } from '../use-auth-ready'
import type { ApiRule, ApiWebhook } from '../types'
import type { RuleEditorState } from '@/lib/mail-automation/types'
import type { RuleSimulationMessage, RuleSimulationResult } from '@/lib/mail-automation/types'
import { workflowToApiPayload } from '@/lib/mail-automation/defaults'

export function useMailRules() {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ['mail-rules'],
    queryFn: async () => {
      const res = await apiClient.get<ApiRule[] | { rules: ApiRule[] }>(
        '/mail/rules'
      )
      return Array.isArray(res) ? res : (res.rules ?? [])
    },
    staleTime: 60_000,
    enabled: ready && authenticated,
    retry: 1,
  })
}

export function useCreateMailRule() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (payload: {
      name: string
      account_id?: string
      priority?: number
      rule_kind?: string
      conditions?: unknown
      actions?: unknown
      workflow?: unknown
    }) => apiClient.post<{ id: string }>('/mail/rules', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-rules'] })
    },
  })
}

export function useUpdateMailRule() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({
      ruleId,
      ...payload
    }: {
      ruleId: string
      name: string
      priority: number
      is_active: boolean
      rule_kind?: string
      conditions?: unknown
      actions?: unknown
      workflow?: unknown
    }) => apiClient.put(`/mail/rules/${ruleId}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-rules'] })
    },
  })
}

export function useDeleteMailRule() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (ruleId: string) => apiClient.delete(`/mail/rules/${ruleId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-rules'] })
    },
  })
}

export function useSimulateMailRule() {
  return useMutation({
    mutationFn: (payload: {
      message: RuleSimulationMessage
      rule_id?: string
      rule?: {
        conditions?: unknown
        actions?: unknown
        workflow?: unknown
      }
    }) => apiClient.post<RuleSimulationResult>('/mail/rules/simulate', payload),
  })
}

export function saveRuleEditorState(
  state: RuleEditorState,
  ruleId?: string
) {
  const payload = workflowToApiPayload(state)
  if (ruleId) {
    return apiClient.put(`/mail/rules/${ruleId}`, payload)
  }
  return apiClient.post<{ id: string }>('/mail/rules', payload)
}

export function useMailWebhooks() {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ['mail-webhooks'],
    queryFn: async () => {
      const res = await apiClient.get<ApiWebhook[] | { webhooks: ApiWebhook[] }>(
        '/mail/webhooks'
      )
      return Array.isArray(res) ? res : (res.webhooks ?? [])
    },
    staleTime: 60_000,
    enabled: ready && authenticated,
    retry: 1,
  })
}

export type MailWebhookPayload = {
  name: string
  url: string
  method?: string
  body_template?: string
  event_types?: string[]
  mail_scope?: ApiWebhook['mail_scope']
  drive_scope?: ApiWebhook['drive_scope']
  contacts_scope?: ApiWebhook['contacts_scope']
  agenda_scope?: ApiWebhook['agenda_scope']
}

export function useCreateMailWebhook() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (payload: MailWebhookPayload) =>
      apiClient.post<{ id: string }>('/mail/webhooks', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-webhooks'] })
    },
  })
}

export function useUpdateMailWebhook() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: ({ webhookId, ...payload }: MailWebhookPayload & { webhookId: string }) =>
      apiClient.put(`/mail/webhooks/${webhookId}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-webhooks'] })
    },
  })
}

export function useDeleteMailWebhook() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (webhookId: string) =>
      apiClient.delete(`/mail/webhooks/${webhookId}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mail-webhooks'] })
    },
  })
}
