import * as fs from 'fs-extra';
import * as path from 'path';
import { getConfig, PageConfig } from '@2fn/conf';

export async function generatePages(targetDir: string) {
  const conf = getConfig();
  if (!conf.pages) {
    throw new Error(`There are no defined pages`);
  }
  const pagesDir = path.join(targetDir, 'pages');
  fs.removeSync(pagesDir);
  console.log(`creating pages`);
  const pagesCreation = Object.entries(conf.pages).map(
    async ([pageName, page]) => {
      try {
        const pageGenerator = require(`./${page.type}Page`).default;
        await pageGenerator({
          pagesDir,
          name: pageName,
          config: page,
        });
      } catch (e) {
        throw new Error(`Unknown page type ${page.type}: ${e}`);
      }
    }
  );
  await Promise.all(pagesCreation);
}

export type PageGeneratorProps<T> = {
  pagesDir: string;
  name: string;
  config: T;
};
