'use client'

import { useQueries, useQuery } from '@tanstack/react-query'
import { apiClient } from '../client'
import { useAuthReady } from '../use-auth-ready'
import { useMailAccounts } from './use-mail-queries'
import type { ApiFolder } from '../types'

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

/** Fetch IMAP folders for every connected mail account. */
export function useImapFolders() {
  const { ready, authenticated } = useAuthReady()
  const { data: accounts = [] } = useMailAccounts()

  const queries = useQueries({
    queries: accounts.map((account) => ({
      queryKey: ['folders', account.id] as const,
      queryFn: async () => {
        const res = await apiClient.get<ApiFolder[] | { folders: ApiFolder[] }>(
          '/mail/folders',
          { account_id: account.id }
        )
        return unwrapFolders(res)
      },
      enabled: ready && authenticated && !!account.id,
      staleTime: 60_000,
      retry: 1,
    })),
  })

  const isLoading = queries.some((q) => q.isLoading)
  const isFetched = accounts.length === 0 || queries.every((q) => q.isFetched)
  const folders = queries.flatMap((q) => q.data ?? [])

  return { folders, isLoading, isFetched }
}

/** IMAP folders for a single mail account. */
export function useImapFoldersForAccount(accountId: string | undefined) {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ['folders', accountId] as const,
    queryFn: async () => {
      const res = await apiClient.get<ApiFolder[] | { folders: ApiFolder[] }>(
        '/mail/folders',
        { account_id: accountId! }
      )
      return unwrapFolders(res)
    },
    enabled: ready && authenticated && !!accountId,
    staleTime: 60_000,
    retry: 1,
  })
}
