const chalk = require('chalk')
const ora = require('ora')
const { getConfig } = require('../lib/config')
const { createPage } = require('../lib/api')
const { metaTagsFromCliOptions } = require('../lib/pages-cli')
const { normalizeContentSlug, isValidContentSlug } = require('../lib/blog-csv')

async function pagesCreateCommand(options) {
  try {
    const appId = options.appId || getConfig('defaultAppId')
    if (!appId) {
      console.error(chalk.red('Error: App ID is required. Use --app-id or set defaultAppId in bild.json.'))
      process.exit(1)
    }

    const rawSlug = String(options.slug ?? '').trim()
    const name = String(options.name ?? '').trim()
    const contentId = String(options.contentId ?? '').trim()

    if (!rawSlug || !name || !contentId) {
      console.error(chalk.red('Error: --slug, --name, and --content-id are required.'))
      process.exit(1)
    }

    const slug = normalizeContentSlug(rawSlug)
    if (!isValidContentSlug(slug)) {
      console.error(chalk.red(`Invalid slug "${rawSlug}" → "${slug}" (use lowercase kebab-case).`))
      process.exit(1)
    }

    const published = options.draft ? false : true
    const metaTags = metaTagsFromCliOptions(options)

    /** @type {Record<string, unknown>} */
    const body = {
      slug,
      name,
      contentId,
      published,
      archived: false,
      deleted: false,
    }

    const preview = options.previewDescription != null ? String(options.previewDescription).trim() : ''
    if (preview) body.previewDescription = preview

    if (metaTags) body.metaTags = metaTags

    const spinner = ora('Creating page…').start()
    try {
      const created = await createPage(appId, body)
      spinner.succeed(chalk.green(`Created page ${created.id || ''} (${slug})`))
      if (process.env.BILD_DEBUG === '1') console.log(JSON.stringify(created, null, 2))
    } catch (e) {
      spinner.fail(e.message || String(e))
      process.exit(1)
    }
  } catch (e) {
    console.error(chalk.red(e.message || String(e)))
    process.exit(1)
  }
}

module.exports = pagesCreateCommand
