/* eslint-disable import/no-extraneous-dependencies */
const dtsgen = require('react-to-typescript-definitions');
const { writeFileSync, mkdirSync } = require('fs');
const path = require('path');
const glob = require('glob');

function getModuleName(url) {
  return path.basename(url).replace('.js', '');
}

function newModuleEntry(moduleName, files) {
  return [
    `declare module "${moduleName}" {`,
    ...files.map((urlPath) => `    export {${getModuleName(
      urlPath
    )}} from "${urlPath.replace('.js', '')}"`),
    '}',
  ].join('\n');
}

// Used to enhance the props interface inferred by adding generic HTML props
const EXTEND_PROPS_STRING = `Props {
    [key: string]: any;`;

const mainFiles = glob.sync('src/react/core/**/*.js', { ignore: '**/*.test.js' });
const formsyFiles = glob.sync('src/react/formsy/**/*.js', { ignore: '**/*.test.js' });
const projectsFiles = glob.sync('src/react/projects/**/*.js', { ignore: '**/*.test.js' });

const definitions = [mainFiles, formsyFiles, projectsFiles].flat().map((urlPath) => {
  const definition = dtsgen.generateFromFile(
    urlPath.replace('.js', ''),
    urlPath
  );

  return definition.replace('Props {', EXTEND_PROPS_STRING);
});
mkdirSync('./react', { recursive: true })
writeFileSync(
  './react/index.d.ts',
  `
  ${newModuleEntry('saagie-ui/react', mainFiles)}\n
  ${newModuleEntry('saagie-ui/react/formsy', formsyFiles)}\n
  ${newModuleEntry('saagie-ui/react/projects', projectsFiles)}\n
  ${definitions.join('')}
  `
);
