"use client"

import { useEffect, useRef } from "react"
import { useQueryClient } from "@tanstack/react-query"
import { apiClient } from "../client"
import { useAuthReady } from "../use-auth-ready"
import type { EmailAttachment } from "@/lib/email-data"
import type { ListAttachmentFetchState } from "./use-list-message-attachments"

/** Re-fetch attachments from IMAP when has_attachments is set but metadata is missing. */
export function useRecoverMissingMessageAttachments(
  messages: { id: string; has_attachments: boolean }[],
  byId: Map<string, EmailAttachment[]>,
  stateById: Map<string, ListAttachmentFetchState>
) {
  const { ready, authenticated } = useAuthReady()
  const queryClient = useQueryClient()
  const attemptedRef = useRef(new Set<string>())

  useEffect(() => {
    if (!ready || !authenticated) return

    for (const msg of messages) {
      if (!msg.has_attachments) continue
      if (stateById.get(msg.id) !== "done") continue
      if ((byId.get(msg.id)?.length ?? 0) > 0) continue
      if (attemptedRef.current.has(msg.id)) continue

      attemptedRef.current.add(msg.id)
      void apiClient
        .post<{ status: string }>(`/mail/messages/${msg.id}/attachments/reindex`)
        .then(() =>
          queryClient.invalidateQueries({
            queryKey: ["message-attachments", msg.id],
          })
        )
        .catch(() => {
          // One attempt per mount — avoid hammering IMAP on permanent failures.
        })
    }
  }, [messages, byId, stateById, ready, authenticated, queryClient])
}
