import * as fs from 'fs';
import * as path from 'path';
import matter from 'gray-matter';
import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import React from 'react';
import { SinglePageTemplate } from '@/components/SinglePageTemplate/SinglePageTemplate';

const pathname = './src/app/[slug]/markdown';

function get_files_path(file_path: string, result: string[] = []) {
  const filenames = fs.readdirSync(file_path);
  for (const filename of filenames) {
    const full_path = path.join(file_path, filename);
    const stats = fs.statSync(full_path);
    if (stats.isFile()) {
      result.push(full_path);
    }
    if (stats.isDirectory()) {
      get_files_path(full_path, result);
    }
  }
  return result;
}

export async function generateStaticParams() {
  // const filenames = fs.readdirSync(pathname).filter((name) => name.endsWith('.md'))
  const paths = get_files_path(pathname).map((value) =>
    value.replaceAll('\\', '/').replaceAll(pathname.slice(2), '').slice(1, -3),
  );
  // console.log({paths})
  const params = paths.map((value) => ({ slug: encodeURIComponent(value) }));
  console.log(params);
  return params;
}

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}): Promise<Metadata> {
  const filePath = path.join(pathname, '/', decodeURIComponent(params.slug) + '.md');
  try {
    const source = await fs.promises.readFile(filePath, 'utf-8');

    const { data, content } = matter(source);

    return {
      ...data,
      description: data.summary || content.substring(0, 150),
    };
  } catch (error) {
    console.error('Error reading file:', error);

    return {
      title: 'Error',
      description: 'Unable to fetch metadata',
    };
  }
}

export default async function SinglePage({ params }: { params: { slug: string } }) {
  const { slug } = params;
  const filePath = path.join(pathname, '/', decodeURIComponent(slug) + '.md');

  try {
    const source = await fs.promises.readFile(filePath, 'utf-8');
    
    return <SinglePageTemplate source={source} />;
  } catch (error) {
    console.error('Error reading file:', error);
    
    notFound();
  }
}
