import type { ChatMessage } from "@/components/chat/ChatMessageCard";

const IMAGE_EXT = ["jpg", "jpeg", "png", "webp", "gif", "avif"];
const VIDEO_EXT = ["mp4", "webm", "mov", "m4v"];
const VOICE_EXT = ["mp3", "wav", "aac", "m4a", "ogg", "opus", "webm"];
const DOC_EXT = ["pdf", "zip", "rar", "doc", "docx", "xls", "xlsx", "txt"];

/** Reliable media type — voice never shown as video */
export function detectChatFileType(
  fileUrl: string,
  declared?: ChatMessage["fileType"]
): ChatMessage["fileType"] | null {
  if (declared === "location") return "location";
  if (declared === "voice") return "voice";
  if (!fileUrl) return declared ?? null;

  const lower = fileUrl.toLowerCase();
  const ext = lower.split(".").pop()?.split("?")[0] || "";

  if (declared === "image" || IMAGE_EXT.includes(ext)) return "image";
  if (declared === "voice") return "voice";
  if (VOICE_EXT.includes(ext) && ext !== "webm") return "voice";
  if (ext === "webm") {
    if (
      lower.includes("voice") ||
      lower.includes("audio") ||
      declared === "voice"
    ) {
      return "voice";
    }
    if (declared === "video" || lower.includes("video")) return "video";
    return "voice";
  }
  if (declared === "video" || VIDEO_EXT.includes(ext)) return "video";
  if (declared === "file" || DOC_EXT.includes(ext)) return "file";

  if (IMAGE_EXT.includes(ext)) return "image";
  if (["mp3", "wav", "aac", "m4a", "opus"].includes(ext)) return "voice";
  if (VIDEO_EXT.includes(ext)) return "video";
  return "file";
}
