const chalk = require('chalk')
const { getConfig } = require('../lib/config')
const { applyLibraryDepsRewrite } = require('../lib/library-deps-hint')
const { applyDepsFileUpdates, depsReportHasPatch } = require('./template-from-jsx-shared')

/**
 * When `options.applyDeps` is true, runs the same pipeline for `bild library add` and
 * `bild library update`: npm packages registered on the cms object, local/@/ re-exports
 * through the Components barrel, and cms + barrel file patches on disk.
 *
 * @param {string} filePath
 * @param {string} code Current file contents
 * @param {{ applyDeps?: boolean, depsFile?: string, sitePath?: string, depsAlias?: string }} options
 * @param {{ label: 'library add' | 'library update' }} ctx
 * @returns {Promise<string>} Code to upload (rewritten or original)
 */
async function applyCmsDependenciesForCodeLibraryIfEnabled(filePath, code, options, { label }) {
  if (!options.applyDeps) {
    return code
  }
  const rewritten = applyLibraryDepsRewrite(filePath, {
    depsFile: options.depsFile,
    sitePath: options.sitePath || getConfig().sitePath,
    depsImportAlias: options.depsAlias,
  })
  let uploadCode = code
  if (rewritten.applied) {
    uploadCode = rewritten.code
    console.log(chalk.green('Applied cmsDependencies rewrites for this upload (source file on disk unchanged).'))
  }
  if (rewritten.report && rewritten.depsFilePath) {
    await applyDepsFileUpdates(rewritten.depsFilePath, rewritten.report, label)
    if (
      depsReportHasPatch(rewritten.report) ||
      (rewritten.report.useBarrelReexports && rewritten.report.barrelReexportLines?.length)
    ) {
      console.log(chalk.dim(`Updated ${rewritten.depsFilePath}`))
    }
  }
  return uploadCode
}

module.exports = { applyCmsDependenciesForCodeLibraryIfEnabled }
