const inquirer = require('inquirer')
const { saveConfig, getConfig, normalizeUrl } = require('../lib/config')
const { writeCmsDependenciesBoilerplate } = require('../lib/cms-dependencies-boilerplate')
const chalk = require('chalk')

async function init() {
  console.log(chalk.blue('Initializing BILD CLI configuration...\n'))

  const config = getConfig()
  const prompt = inquirer.createPromptModule()
  const answers = await prompt([
    {
      type: 'input',
      name: 'cmsUrl',
      message: 'BILDIT CMS instance URL:',
      default: config.cmsUrl,
      validate: (input) => {
        if (!input) return 'CMS URL is required'
        try {
          new URL(input)
          return true
        } catch {
          return 'Please enter a valid URL'
        }
      },
    },
    {
      type: 'input',
      name: 'defaultAppId',
      message: 'Default App ID (optional):',
      default: config.defaultAppId,
    },
    {
      type: 'input',
      name: 'defaultApiKey',
      message: 'Default API Key (optional):',
      default: config.defaultApiKey,
    },
    {
      type: 'input',
      name: 'reactVersion',
      message: 'React version:',
      default: config.reactVersion || '18.2.0',
    },
    {
      type: 'input',
      name: 'sitePath',
      message: 'Path to consumer website (for cmsDependencies; optional):',
      default: config.sitePath || '',
    },
    {
      type: 'input',
      name: 'cmsDependenciesFile',
      message: 'cmsDependencies file path (relative to site path):',
      default: config.cmsDependenciesFile || 'src/cmsDependencies.ts',
    },
    {
      type: 'input',
      name: 'cmsDependenciesImportAlias',
      message: 'cmsDependencies import alias:',
      default: config.cmsDependenciesImportAlias || '@/cmsDependencies',
    },
    {
      type: 'confirm',
      name: 'createCmsDepsBoilerplate',
      message: (a) =>
        `Create boilerplate ${a.cmsDependenciesFile} under ${a.sitePath}? (skipped if the file already exists)`,
      default: true,
      when: (a) => Boolean(a.sitePath && String(a.sitePath).trim()),
    },
    {
      type: 'list',
      name: 'cssMode',
      message: 'Default CSS mode for `template legacy from-jsx`:',
      choices: ['hybrid', 'inline', 'style-tag'],
      default: config.cssMode || 'hybrid',
    },
    {
      type: 'list',
      name: 'namingStrategy',
      message: 'Default field naming strategy:',
      choices: ['camelComponent', 'layerPath'],
      default: config.namingStrategy || 'camelComponent',
    },
  ])

  const newConfig = {
    ...config,
    ...answers,
    // Normalize CMS URL to remove trailing slashes
    cmsUrl: answers.cmsUrl ? normalizeUrl(answers.cmsUrl) : config.cmsUrl,
    // Empty string means "unset"; preserve null so downstream checks work.
    sitePath: answers.sitePath ? answers.sitePath : null,
  }

  if (saveConfig(newConfig)) {
    console.log(chalk.green('\n✓ Configuration saved successfully!'))

    if (
      newConfig.sitePath &&
      answers.createCmsDepsBoilerplate &&
      newConfig.cmsDependenciesFile
    ) {
      const result = writeCmsDependenciesBoilerplate(
        newConfig.sitePath,
        newConfig.cmsDependenciesFile,
      )
      if (!result.ok) {
        console.log(
          chalk.yellow(
            `\nCould not create cmsDependencies boilerplate (${result.reason}): ${result.path}`,
          ),
        )
      } else if (result.skipped) {
        console.log(chalk.dim(`\ncmsDependencies already exists — skipped: ${result.path}`))
      } else {
        console.log(chalk.green(`\n✓ Created cmsDependencies boilerplate: ${result.path}`))
      }
    }

    console.log(chalk.yellow('\nNext steps:'))
    console.log(chalk.yellow('  - Run "bild login" to authenticate'))
    console.log(chalk.yellow('  - Run "bild upload <files>" to upload Templates source files'))
  } else {
    console.error(chalk.red('\n✗ Failed to save configuration'))
    process.exit(1)
  }
}

module.exports = init

