import * as fs from 'fs-extra';
import * as path from 'path';
import { createOrAppendToFile } from './generationUtils';

export async function createPage(
  pagesDir: string,
  name: string,
  content: string
) {
  const fileName = path.join(pagesDir, `${name}.js`);
  await fs.ensureFile(fileName);
  createOrAppendToFile(fileName, getPageTemplate(name, content));
  return fileName;
}

export function createSimpleGetStaticProps(name: string, category: string) {
  createOrAppendToFile(
    name,
    `export async function getStaticProps(context) {
	const data = await fetchData('${category}');
	return {
    props: { data },
    unstable_revalidate: 1,
	};
}`
  );
}

export function createDynamicGetStaticProps(name: string, category: string) {
  createOrAppendToFile(
    name,
    `export async function getStaticProps(context) {
  const id = context.params?.id;
  console.log('***id', id);
	const data = await fetchData(\`${category}\${id}\`);
	return {
    props: { data },
    unstable_revalidate: 1,
	};
}`
  );
}

export function createGetStaticPaths(
  name: string,
  dataCategory: string,
  dataKey: string
) {
  createOrAppendToFile(
    name,
    `export async function getStaticPaths() {
    const data = await fetchData('${dataCategory}');
    console.log('***data', data);
    return {
      paths: data.map(item => ({ params: {id: item['${dataKey}'].toString()} })),
      fallback: true
    };
  }`
  );
}

function getPageTemplate(name: string, content: string) {
  return `import React from 'react';
import Link from 'next/link';
import {fetchData} from '@2fn/data';

export default function ${getPageName(name)}({data}) {
	return (
		<div>
			${content}
		</div>
	);
}
	`;
}

function getPageName(name: string) {
  const shortName = name.split('/')[0];
  return `${shortName[0].toUpperCase()}${shortName.slice(1)}`;
}
