import type { Person } from "@/data/mockApplications";
import { getAccessToken } from "@/shared/utils/token";
import { toast } from "sonner";

/** Single path segment / basename fragment — mirrors backend intent for `{username}_{applicationId}.zip`. */
export function sanitizeBackupUsernameSegment(raw: string): string {
  const s = raw
    .replace(/[/\\]/g, "_")
    .replace(/\s+/g, "_")
    .replace(/[\u0000-\u001f]/g, "")
    .trim();
  return (s.slice(0, 80) || "applicant").replace(/_+/g, "_");
}

export function buildApplicationBackupZipFilename(
  applicationId: string,
  author?: Pick<Person, "email" | "name"> | null,
): string {
  let user = "applicant";
  const email = author?.email?.trim();
  if (email && email.includes("@")) {
    user = sanitizeBackupUsernameSegment(email.split("@")[0] ?? "applicant");
  } else if (author?.name?.trim()) {
    user = sanitizeBackupUsernameSegment(author.name.trim());
  }
  const id = (applicationId || "").trim() || "unknown";
  return `${user}_${id}.zip`;
}

export function parseFilenameFromContentDisposition(header: string | null): string | null {
  if (!header) return null;
  const utf8 = header.match(/filename\*=(?:UTF-8''|utf-8'')([^;\n]+)/i);
  if (utf8?.[1]) {
    try {
      return decodeURIComponent(utf8[1].trim().replace(/^"+|"+$/g, ""));
    } catch {
      /* ignore */
    }
  }
  const quoted = header.match(/filename="((?:\\.|[^"\\])*)"/i);
  if (quoted?.[1]) {
    return quoted[1].replace(/\\(.)/g, "$1");
  }
  const plain = header.match(/filename=([^;\n]+)/i);
  if (plain?.[1]) {
    return plain[1].trim().replace(/^"+|"+$/g, "");
  }
  return null;
}

/**
 * GET /api/applications/:id/backup — saves ZIP; filename from Content-Disposition when present.
 */
export async function downloadApplicationBackupArchive(
  applicationId: string,
  author?: Pick<Person, "email" | "name"> | null,
): Promise<void> {
  const token = getAccessToken();
  try {
    const res = await fetch(`/api/applications/${encodeURIComponent(applicationId)}/backup`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    });
    if (!res.ok) {
      let msg = res.statusText;
      try {
        const body = (await res.json()) as { detail?: string };
        if (typeof body.detail === "string") msg = body.detail;
      } catch {
        /* ignore */
      }
      toast.error(msg || "Không tải được bản sao lưu.");
      return;
    }
    const blob = await res.blob();
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    const fromHeader = parseFilenameFromContentDisposition(res.headers.get("Content-Disposition"));
    a.download = fromHeader || buildApplicationBackupZipFilename(applicationId, author);
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
    toast.success("Đã tải bản sao lưu (ZIP).");
  } catch {
    toast.error("Lỗi mạng khi tải bản sao lưu.");
  }
}
