"use client"

import { useQuery } from "@tanstack/react-query"
import { apiClient } from "../client"
import { useAuthReady } from "../use-auth-ready"
import {
  mapApiAttachmentsToEmail,
  type ApiMessageAttachment,
} from "../map-message-attachments"
import type { EmailAttachment } from "@/lib/email-data"

type AttachmentsResponse = {
  attachments?: ApiMessageAttachment[]
}

export function fetchMessageAttachments(
  messageId: string
): Promise<EmailAttachment[]> {
  return apiClient
    .get<AttachmentsResponse>(`/mail/messages/${messageId}/attachments`)
    .then((res) => mapApiAttachmentsToEmail(res.attachments))
}

export function useMessageAttachments(
  messageId: string | undefined,
  enabled = true
) {
  const { ready, authenticated } = useAuthReady()

  return useQuery({
    queryKey: ["message-attachments", messageId],
    queryFn: () => fetchMessageAttachments(messageId!),
    enabled: ready && authenticated && enabled && Boolean(messageId),
    staleTime: 5 * 60_000,
  })
}
