import legacyData from "@/data/legacy-content.json";

export type LegacyPost = {
  id: number;
  slug: string;
  title: string;
  type: "post" | "page" | string;
  date: string;
  excerpt: string;
  featuredImage: string;
  images: string[];
  html: string;
};

export type LegacySource = {
  sqlFile: string;
  siteurl: string;
  home: string;
  generatedAt: string;
};

export type LegacyStats = {
  candidatePosts: number;
  exportedPosts: number;
  imagesFound: number;
  imagesDownloaded: number;
  imagesSkipped: number;
  typeCounts: Record<string, number>;
  truncatedTo?: number;
};

export type LegacyPayload = {
  source: LegacySource;
  stats: LegacyStats;
  posts: LegacyPost[];
};

const payload = legacyData as unknown as LegacyPayload;

export function getLegacyPayload(): LegacyPayload {
  return payload;
}

export function getLegacyPosts(): LegacyPost[] {
  return payload.posts;
}

export function getLegacyPostBySlug(slug: string): LegacyPost | undefined {
  return payload.posts.find((p) => p.slug === slug);
}

export function formatLegacyDate(raw: string): string {
  if (!raw) return "";
  // Stored as "YYYY-MM-DD HH:MM:SS" from the dump.
  const iso = raw.includes("T") ? raw : raw.replace(" ", "T");
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return raw;
  return d.toLocaleDateString("en-GB", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}
