const inquirer = require('inquirer')
const chalk = require('chalk')
const ora = require('ora')
const { getConfig } = require('../lib/config')
const { deleteCodeLibrary, getCodeLibrary } = require('../lib/api')
const { requireDeveloperRoleForApp } = require('../lib/roles')
const { resolveLibraryTemplateId } = require('../lib/cli-cid')

async function deleteCommand(positionalTemplateId, options) {
  try {
    const config = getConfig()
    const appId = options.appId || config.defaultAppId
    const templateId = resolveLibraryTemplateId(options, positionalTemplateId)

    if (!appId) {
      console.error(chalk.red('Error: App ID is required. Use --app-id or set defaultAppId in config.'))
      process.exit(1)
    }

    if (!templateId || String(templateId).trim() === '') {
      console.error(
        chalk.red(
          'Error: Template ID is required. Use: bild library delete --template-id <id>  (e.g. --template-id=-x for values starting with a hyphen), or bild library delete -- <id>',
        ),
      )
      process.exit(1)
    }

    await requireDeveloperRoleForApp(appId)

    const spinner = ora('Loading template...').start()
    let item
    try {
      item = await getCodeLibrary(appId, templateId)
    } catch (error) {
      spinner.fail(`Could not load template: ${error.message}`)
      process.exit(1)
    }
    spinner.stop()

    const templateLabel = item.templateId || item.snippetId || templateId
    const displayName = item.name ? `${item.name} (${templateLabel})` : templateLabel

    if (!options.yes) {
      const prompt = inquirer.createPromptModule()
      const { confirmed } = await prompt([
        {
          type: 'confirm',
          name: 'confirmed',
          default: false,
          message: `Delete template ${chalk.bold(displayName)} (Template ID ${chalk.bold(templateId)}) from app ${chalk.bold(appId)}?`,
        },
      ])
      if (!confirmed) {
        console.log(chalk.yellow('Cancelled.'))
        process.exit(0)
      }
    }

    const delSpinner = ora('Deleting template...').start()
    try {
      await deleteCodeLibrary(appId, templateId)
      delSpinner.succeed(`Deleted template ${displayName} (Template ID ${templateId})`)
    } catch (error) {
      delSpinner.fail(`Delete failed: ${error.message}`)
      process.exit(1)
    }
  } catch (error) {
    console.error(chalk.red('\n\u2717 Delete failed: ' + error.message))
    process.exit(1)
  }
}

module.exports = deleteCommand
