import fs from "fs";
import matter from "gray-matter";
import path from "path";

export const LEGAL_SLUGS = [
  "return-and-refund-policy",
  "terms-of-service",
  "privacy-policy",
  "data-protection",
  "general-terms-and-conditions",
] as const;

export type LegalSlug = (typeof LEGAL_SLUGS)[number];

export type LegalDocData = {
  title?: string;
  description?: string;
  lastUpdated?: string;
};

export type LegalDoc = {
  data: LegalDocData;
  content: string;
};

function getContentDir(): string {
  const cwd = process.cwd();
  const direct = path.join(cwd, "content", "legal");
  if (fs.existsSync(direct)) return direct;
  const fromRoot = path.join(cwd, "apps", "storefront", "content", "legal");
  if (fs.existsSync(fromRoot)) return fromRoot;
  return direct;
}

/**
 * Reads and parses a legal markdown file. Server-only; use in Server Components.
 * Returns null if slug is invalid or file is missing (call notFound() in the page).
 */
export function getLegalDoc(slug: string): LegalDoc | null {
  if (!LEGAL_SLUGS.includes(slug as LegalSlug)) return null;
  const contentDir = getContentDir();
  const filePath = path.join(contentDir, `${slug}.md`);
  if (!fs.existsSync(filePath)) return null;
  try {
    const raw = fs.readFileSync(filePath, "utf-8");
    const { data, content } = matter(raw);
    return {
      data: {
        title: data.title as string | undefined,
        description: data.description as string | undefined,
        lastUpdated: data.lastUpdated as string | undefined,
      },
      content: content.trim(),
    };
  } catch {
    return null;
  }
}
