import * as path from 'path';
import * as fs from 'fs';
import { generateProject } from '../generation/generateProject';
import { generatePages } from '../generation/generatePages';
const execa = require('execa');

export async function build() {
  console.log(`build`);
  const targetDir = path.resolve(__dirname, `../../generated`);
  await generateProject(targetDir);
  await generatePages(targetDir);
  const pkgPath = `${process.cwd()}/package.json`;
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
  const pkgName = pkg.name;
  await execa(`mv`, [
    `${targetDir}/pages`,
    `${targetDir}/package.json`,
    `${targetDir}/next.config.js`,
    process.cwd(),
  ]);
  const updatedPkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
  updatedPkg.name = pkgName;
  updatedPkg.dependencies['@2fn/data'] = 'latest';
  fs.writeFileSync(pkgPath, JSON.stringify(updatedPkg, null, 2));
  // const page = fs
  //   .readFileSync(`${process.cwd()}/pages/index.js`, 'utf-8')
  //   .replace('../', '@2fn/data');
  // fs.writeFileSync(`${process.cwd()}/pages/index.js`, page);
  const { stdout: yarnStdout } = await execa('yarn', [], {
    cwd: process.cwd(),
  });
  console.log(yarnStdout);
  const { stdout: buildStdout } = await execa('npm', ['run', 'build'], {
    cwd: process.cwd(),
  });
  console.log(buildStdout);
}
