/* eslint-disable @typescript-eslint/no-floating-promises */
import fs from 'fs'
import { compile } from 'json-schema-to-typescript'

import type { SanitizedConfig } from '../config/types.js'

import { configToJSONSchema } from '../utilities/configToJSONSchema.js'
import Logger from '../utilities/logger.js'

export function generateTypes(config: SanitizedConfig): void {
  const logger = Logger()
  const outputFile = process.env.PAYLOAD_TS_OUTPUT_PATH || config.typescript.outputFile

  logger.info('Compiling TS types for Collections and Globals...')

  const jsonSchema = configToJSONSchema(config, config.db.defaultIDType)

  const declare = `declare module 'payload' {\n  export interface GeneratedTypes extends Config {}\n}`

  compile(jsonSchema, 'Config', {
    bannerComment:
      '/* tslint:disable */\n/* eslint-disable */\n/**\n* This file was automatically generated by Payload.\n* DO NOT MODIFY IT BY HAND. Instead, modify your source Payload config,\n* and re-run `payload generate:types` to regenerate this file.\n*/',
    style: {
      singleQuote: true,
    },
    // Generates code for $defs that aren't referenced by the schema. Reason:
    // If a field defines an interfaceName, it should be included in the generated types
    // even if it's not used by another type. Reason: the user might want to use it in their own code.
    unreachableDefinitions: true,
  }).then((compiled) => {
    if (config.typescript.declare !== false) {
      compiled += `\n\n${declare}`
    }
    fs.writeFileSync(outputFile, compiled)
    logger.info(`Types written to ${outputFile}`)
  })
}
