'use client'

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '../client'
import { useAuthReady } from '../use-auth-ready'
import type { ApiUnifiedFolder } from '../types'

function unwrapFolders(
  res: ApiUnifiedFolder[] | { folders: ApiUnifiedFolder[] }
): ApiUnifiedFolder[] {
  return Array.isArray(res) ? res : (res.folders ?? [])
}

export function useUnifiedFolders(scope: 'all' | 'global' | string = 'all') {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ['unified-folders', scope],
    queryFn: async () => {
      const params =
        scope === 'all'
          ? undefined
          : scope === 'global'
            ? { account_id: 'global' }
            : { account_id: scope }
      const res = await apiClient.get<ApiUnifiedFolder[] | { folders: ApiUnifiedFolder[] }>(
        '/mail/unified-folders',
        params
      )
      return unwrapFolders(res)
    },
    enabled: ready && authenticated,
    staleTime: 60_000,
    retry: 1,
  })
}

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

  return useMutation({
    mutationFn: (payload: {
      name: string
      color?: string
      account_id?: string
      parent_id?: string
    }) => apiClient.post<{ id: string }>('/mail/unified-folders', payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unified-folders'] })
    },
  })
}

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

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

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

  return useMutation({
    mutationFn: ({
      id,
      ...payload
    }: {
      id: string
      name: string
      color: string
      sort_order?: number
      parent_id?: string | null
    }) => apiClient.put(`/mail/unified-folders/${id}`, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unified-folders'] })
    },
  })
}

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

  return useMutation({
    mutationFn: (items: { id: string; sort_order: number; parent_id: string | null }[]) =>
      apiClient.post<void>('/mail/unified-folders/reorder', { items }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['unified-folders'] })
    },
  })
}
