import * as fs from 'fs-extra';
import * as path from 'path';
import { getConfig } from '@2fn/conf';
import { createOrAppendToFile } from './generationUtils';

export async function generateProject(targetDir: string) {
  const conf = getConfig();
  if (!conf.pages) {
    throw new Error(`There are no defined pages`);
  }
  // try {
  //   fs.readdirSync(targetDir);
  //   console.log(`project already created, bailing`);
  //   return;
  // } catch (e) {}
  console.log(`creating project`);
  await fs.remove(targetDir);
  await fs.ensureDir(targetDir);
  console.log(`linking node modules`);
  await linkNodeModules(targetDir);
  console.log(`creating package.json`);
  createPackageJson(targetDir);
  console.log(`creating next config`);
  createNextConfig(targetDir);
}

async function linkNodeModules(targetDir: string) {
  await fs.ensureSymlink('../node_modules', `${targetDir}/node_modules`);
}

function createPackageJson(targetDir: string) {
  createOrAppendToFile(
    path.join(targetDir, 'package.json'),
    JSON.stringify(
      {
        name: '@2fn/generated',
        version: '1.0.0',
        scripts: {
          dev: 'next',
          build: 'next build',
          start: 'next start',
        },
        dependencies: {
          next: '^9.4.2',
          react: '^16.13.1',
          'react-dom': '^16.13.1',
          '@2fn/data': '^1.0.0',
        },
        devDependencies: {
          '@types/react': '^16.9.35',
          typescript: '^3.9.3',
        },
      },
      null,
      2
    )
  );
}
function createNextConfig(targetDir: string) {
  createOrAppendToFile(
    path.join(targetDir, 'next.config.js'),
    `module.exports = {
  target: 'serverless',
	webpack: config => {
		config.node = {
			fs: 'empty'
		}

	return config
	}
}
`
  );
}
