import fs from 'fs-extra'
import { resolve, join } from 'path'
import { packages } from './packages'

const DIR_ROOT = resolve(__dirname, '..', '..')
const DIR_SRC = resolve(DIR_ROOT, 'packages')

export async function updatePackageJSON() {
  const { version } = await fs.readJSON('package.json')

  for (const { name, description } of packages) {
    const packageDir = join(DIR_SRC, name)
    const packageJSONPath = join(packageDir, 'package.json')
    const packageJSON = await fs.readJSON(packageJSONPath)

    packageJSON.version = version
    packageJSON.description = description || packageJSON.description
    packageJSON.main = './index.js'
    packageJSON.types = './index.d.ts'
    packageJSON.module = './index.mjs'
    packageJSON.exports = {
      '.': {
        import: './index.mjs',
        require: './index.cjs',
        types: './index.d.ts',
      },
      './*': './*',
      ...packageJSON.exports,
    }

    await fs.writeJSON(packageJSONPath, packageJSON, { spaces: 2 })
  }
}
