import path from "node:path";
import { findGatedBundleOption, gatedBundleOptions } from "@/data/gated-bundles";

const defaultGatedBundleSlug = "mpc-free-explorer-pack";

const bundleFileBySlug: Record<string, string> = {
  "mpc-free-explorer-pack": "mpc-free-explorer-pack.zip",
  "marloth-kruger-visitor-guide-set": "mpc-free-explorer-pack.zip",
  "mpc-premium-kruger-visitor-map-free": "mpc-premium-kruger-visitor-map-free.zip",
  "marloth-park-international-visitor-checklist": "marloth-park-international-visitor-checklist-pack.zip",
};

const canonicalSlugBySlug: Record<string, string> = {
  "marloth-kruger-visitor-guide-set": defaultGatedBundleSlug,
};

export function normalizeGatedBundleSlug(value: unknown) {
  const slug = String(value || "").trim().toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
  return bundleFileBySlug[slug] ? slug : defaultGatedBundleSlug;
}

export function getGatedBundle(slugValue: unknown) {
  const requestedSlug = normalizeGatedBundleSlug(slugValue);
  const slug = canonicalSlugBySlug[requestedSlug] || requestedSlug;
  const option = findGatedBundleOption(slug);
  const fileName = bundleFileBySlug[requestedSlug];
  return {
    ...option,
    slug,
    fileName,
    absolutePath: path.join(process.cwd(), "private", "gated-bundles", fileName),
  };
}

export function gatedBundleSlugSet() {
  return new Set([...gatedBundleOptions.map((bundle) => bundle.slug), ...Object.keys(bundleFileBySlug)]);
}

export function safeBundleFileDownloadName(slugValue: unknown) {
  const bundle = getGatedBundle(slugValue);
  if (bundle.slug === "mpc-premium-kruger-visitor-map-free") return "MPC-Premium-Kruger-Visitor-Map-Free.zip";
  if (bundle.slug === "marloth-park-international-visitor-checklist") return "MPC-Marloth-Park-International-Visitor-Checklist-Pack.zip";
  return "MPC-Free-Explorer-Guide.zip";
}
