"use client"

import { useMemo } from "react"
import { useQueries } from "@tanstack/react-query"
import { useAuthReady } from "../use-auth-ready"
import { fetchMessageAttachments } from "./use-message-attachments"
import type { EmailAttachment } from "@/lib/email-data"

export type ListAttachmentFetchState = "idle" | "loading" | "done"

export function useListMessageAttachments(messageIds: string[]) {
  const { ready, authenticated } = useAuthReady()
  const stableIds = useMemo(
    () => [...new Set(messageIds)].sort(),
    [messageIds]
  )

  const queries = useQueries({
    queries: stableIds.map((id) => ({
      queryKey: ["message-attachments", id] as const,
      queryFn: () => fetchMessageAttachments(id),
      enabled: ready && authenticated,
      staleTime: 5 * 60_000,
    })),
  })

  return useMemo(() => {
    const byId = new Map<string, EmailAttachment[]>()
    const stateById = new Map<string, ListAttachmentFetchState>()

    stableIds.forEach((id, index) => {
      const q = queries[index]
      if (!q) {
        stateById.set(id, "idle")
        return
      }
      if (q.isPending || q.isFetching) {
        stateById.set(id, "loading")
        return
      }
      stateById.set(id, "done")
      if (q.data?.length) byId.set(id, q.data)
    })

    return { byId, stateById }
  }, [stableIds, queries])
}
