"use client"

import { useQuery } from "@tanstack/react-query"
import { apiClient } from "../client"
import { useAuthReady } from "../use-auth-ready"
import { normalizeCidKey } from "@/lib/mail-cid"
import {
  type ApiMessageAttachment,
} from "../map-message-attachments"

type CidMapResponse = {
  cid_map?: Record<string, string>
}

type AttachmentsResponse = {
  attachments?: ApiMessageAttachment[]
}

function mergeAttachmentIntoCidMap(
  map: Record<string, string>,
  att: ApiMessageAttachment
): void {
  if (!att.is_inline || !att.id) return
  if (att.content_id) {
    const key = normalizeCidKey(att.content_id)
    map[key] = att.id
    map[key.toLowerCase()] = att.id
    map[`cid:${key}`] = att.id
    map[`cid:${key.toLowerCase()}`] = att.id
  }
  if (att.filename) {
    const base = att.filename.includes("/")
      ? att.filename.split("/").pop()!
      : att.filename
    const key = normalizeCidKey(base)
    map[key] = att.id
    map[key.toLowerCase()] = att.id
    map[`cid:${key}`] = att.id
    map[`cid:${key.toLowerCase()}`] = att.id
  }
}

async function fetchMessageCidMap(messageId: string): Promise<Record<string, string>> {
  const [cidRes, listRes] = await Promise.all([
    apiClient.get<CidMapResponse>(
      `/mail/messages/${messageId}/attachments/cid-map`
    ),
    apiClient.get<AttachmentsResponse>(
      `/mail/messages/${messageId}/attachments`
    ),
  ])

  const map: Record<string, string> = { ...(cidRes?.cid_map ?? {}) }
  for (const att of listRes?.attachments ?? []) {
    mergeAttachmentIntoCidMap(map, att)
  }
  return map
}

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

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