import { marked } from 'marked';
import type { LoadedPage } from '@/server/page-layout/loader';
import { loadData as loadRichTextData } from '@/server/page-layout/modules/rich-text-content/loadData';

export const LEGAL_KINDS = ['privacy', 'terms', 'tos-vendor', 'vouchers', 'cookies'] as const;
export type LegalKind = (typeof LEGAL_KINDS)[number];

const KIND_FILE_BASE: Record<LegalKind, string> = {
  privacy: 'privacy',
  terms: 'tos-user',
  'tos-vendor': 'tos-vendor',
  vouchers: 'vouchers',
  cookies: 'cookies',
};

const HERO_IDS: Record<LegalKind, string> = {
  privacy: '00000000-0000-4000-9001-000000000003',
  terms: '00000000-0000-4000-9001-000000000004',
  'tos-vendor': '00000000-0000-4000-9001-000000000005',
  vouchers: '00000000-0000-4000-9001-000000000006',
  cookies: '00000000-0000-4000-9001-000000000007',
};

const CONTENT_IDS: Record<LegalKind, string> = {
  privacy: '00000000-0000-4000-9002-000000000003',
  terms: '00000000-0000-4000-9002-000000000004',
  'tos-vendor': '00000000-0000-4000-9002-000000000005',
  vouchers: '00000000-0000-4000-9002-000000000006',
  cookies: '00000000-0000-4000-9002-000000000007',
};

const rawModules = import.meta.glob('./*.md', {
  query: '?raw',
  import: 'default',
  eager: true,
}) as Record<string, string>;

export function parseMarkdownDocument(raw: string | undefined): { title: string; html: string } {
  if (!raw) return { title: '', html: '' };
  const frontmatter = raw.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?/);
  const encodedTitle = frontmatter?.[1]?.match(/^title:\s*(.+?)\s*$/m)?.[1] ?? '';
  const quoted = encodedTitle.match(/^(['"])(.*)\1$/);
  return {
    title: quoted?.[2] ?? encodedTitle,
    html: marked.parse(frontmatter ? raw.slice(frontmatter[0].length) : raw) as string,
  };
}

function readLocaleFile(kind: LegalKind, locale: 'he' | 'en'): { title: string; html: string } {
  const base = KIND_FILE_BASE[kind];
  return parseMarkdownDocument(rawModules[`./${base}.${locale}.md`]);
}

export function isLegalKind(value: string): value is LegalKind {
  return (LEGAL_KINDS as readonly string[]).includes(value);
}

export async function buildLegalPageFromContent(
  kind: LegalKind,
  locale: 'he' | 'en',
): Promise<LoadedPage> {
  const he = readLocaleFile(kind, 'he');
  const en = readLocaleFile(kind, 'en');
  const heroTitle = {
    he: he.title || kind,
    en: en.title || kind,
  };
  const body = {
    he: he.html,
    en: en.html,
  };
  const richTextData = await loadRichTextData(null as never, { body }, { locale, isGuest: true });
  const modules = [
    {
      instanceId: HERO_IDS[kind],
      type: 'page-hero',
      config: { title: heroTitle, subtitle: { he: '', en: '' } },
      data: null,
    },
    {
      instanceId: CONTENT_IDS[kind],
      type: 'rich-text-content',
      config: { body },
      data: richTextData,
    },
  ];

  return {
    mobile: modules,
    desktop: modules,
  };
}
