const chalk = require('chalk')
const { getConfig } = require('../lib/config')
const { listPages } = require('../lib/api')
const { normalizePagesListResponse } = require('../lib/pages-cli')

async function pagesListCommand(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 params = {}
    if (options.slug) params.slug = String(options.slug).trim()
    if (options.draft === true) params.draft = true
    if (options.published === true) params.published = true
    if (options.archived === true) params.archived = true

    const raw = await listPages(appId, params)
    const pages = normalizePagesListResponse(raw)

    if (options.json) {
      console.log(JSON.stringify(pages, null, 2))
      return
    }

    if (pages.length === 0) {
      console.log(chalk.yellow('No pages found.'))
      return
    }

    console.log(chalk.blue(`Pages (${pages.length})\n`))
    for (const p of pages) {
      const id = p.id != null ? String(p.id) : ''
      const slug = p.slug != null ? String(p.slug) : ''
      const name = p.name != null ? String(p.name) : ''
      const pub = p.published === true ? chalk.green('yes') : chalk.yellow('no')
      const cid = p.contentId != null ? String(p.contentId) : chalk.dim('—')
      console.log(
        `${chalk.bold(id)}  ${chalk.cyan(slug)}  ${name}  published:${pub}  contentId:${cid}`,
      )
    }
  } catch (e) {
    console.error(chalk.red(e.message || String(e)))
    process.exit(1)
  }
}

module.exports = pagesListCommand
