// A script to be executed post hydra codegen, that may include modifications to autogenerated files
import fs from 'fs'
import path from 'path'

// TS4 useUnknownInCatchVariables is not compatible with auto-generated code inside generated/graphql-server
const serverTsConfigPath = path.resolve(__dirname, '../../generated/graphql-server/tsconfig.json')
const serverTsConfig = JSON.parse(fs.readFileSync(serverTsConfigPath).toString())
serverTsConfig.compilerOptions.useUnknownInCatchVariables = false
fs.writeFileSync(serverTsConfigPath, JSON.stringify(serverTsConfig, undefined, 2))

// Type assertions are no longer needed for createTypeUnsafe in @polkadot/api 5.9.1 (and they break the build)
// Here we're relpacing createTypeUnsafe<Assertions>(...params) to createTypeUnsafe(...params) in all generated types:
const generatedTypesPaths = path.resolve(__dirname, '../generated/types')
fs.readdirSync(generatedTypesPaths).map((fileName) => {
  if (path.extname(fileName) === '.ts') {
    const filePath = path.join(generatedTypesPaths, fileName)
    const fileContent = fs.readFileSync(filePath).toString()
    fs.writeFileSync(filePath, fileContent.replace(/createTypeUnsafe<[^(]+[(]/g, 'createTypeUnsafe('))
  }
})
