import { mockVideoBehavior } from "@/mock-video/behavior.config";

export function makeArchiveFilename(input: string, sourceFilename: string) {
  const cleaned = input.normalize("NFKD").replace(/[^\p{L}\p{N}\s-]/gu, " ").trim();
  const words = cleaned.split(/\s+/).filter(Boolean).slice(0, mockVideoBehavior.fileNaming.wordsFromUserInput);
  const slug = (words.join("_") || mockVideoBehavior.fileNaming.fallback).toLowerCase().replace(/[-\s]+/g, "_");
  const suffix = Math.random().toString(36).slice(2, 6);
  const extensionMatch = sourceFilename.match(/\.[a-z0-9]+$/i);
  const extension = extensionMatch?.[0] || mockVideoBehavior.fileNaming.extension;
  return `${mockVideoBehavior.fileNaming.prefix}${slug}_${suffix}${extension}`;
}

export async function downloadMockArchive(input: string) {
  const pointerResponse = await fetch(mockVideoBehavior.downloadFilePointer, { cache: "no-store" });
  if (!pointerResponse.ok) throw new Error("The download filename could not be loaded.");
  const sourceFilename = (await pointerResponse.text()).trim();
  if (!sourceFilename || sourceFilename.includes("/") || sourceFilename.includes("\\")) {
    throw new Error("The download filename is invalid.");
  }
  const response = await fetch(`/mock-video/${encodeURIComponent(sourceFilename)}`, { cache: "no-store" });
  if (!response.ok) throw new Error("The video archive could not be loaded.");
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = makeArchiveFilename(input, sourceFilename);
  document.body.appendChild(anchor);
  anchor.click();
  anchor.remove();
  window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
