import React from 'react';
import { GetStaticProps, GetStaticPaths } from 'next';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import ReactMarkdown from 'react-markdown';

interface PolicyProps {
  content: string;
}

const PolicyPage: React.FC<PolicyProps> = ({ content }) => {
  return (
    <div className="container mx-auto py-8">
      <ReactMarkdown>{content}</ReactMarkdown>
    </div>
  );
};

export const getStaticPaths: GetStaticPaths = async () => {
  const policiesDir = path.join(process.cwd(), 'content', 'policies');
  const policyFolders = fs.readdirSync(policiesDir);

  const paths = policyFolders.flatMap((folder) => {
    const languageFiles = fs.readdirSync(path.join(policiesDir, folder));
    return languageFiles.map((file) => {
      return { params: { slug: folder, fileName: file } };
    });
  });

  return {
    paths,
    fallback: false,
  };
};

export const getStaticProps: GetStaticProps<PolicyProps> = async ({ params }) => {
  const { slug, fileName } = params as { slug: string; fileName: string };
  const filePath = path.join(process.cwd(), 'content', 'policies', slug, fileName);
  const fileContent = fs.readFileSync(filePath, 'utf-8');
  const { content } = matter(fileContent);

  return {
    props: {
      content,
    },
  };
};

export default PolicyPage;
