const chalk = require('chalk')
const { getConfig } = require('../lib/config')
const { listBanners } = require('../lib/api')

async function listBannersCommand(options) {
  try {
    const config = getConfig()
    const cmsUrl = config.cmsUrl

    if (!cmsUrl) {
      console.error(chalk.red('Error: CMS URL not configured. Run "bild init" first.'))
      process.exit(1)
    }

    const appId = options.appId || config.defaultAppId

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

    console.log(chalk.blue(`Fetching banners for app ${chalk.bold(appId)}...\n`))

    try {
      const data = await listBanners(appId, options)
      const banners = Array.isArray(data)
        ? data
        : data?.data ?? data?.banners ?? data?.items ?? Object.values(data ?? {})

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

      console.log(chalk.bold('Banners:\n'))
      console.log(chalk.gray('─'.repeat(80)))

      banners.forEach((banner) => {
        const id = banner.id ?? 'N/A'
        console.log(`${chalk.cyan('ID')}: ${chalk.bold(id)}`)

        if (banner.name) {
          console.log(`  ${chalk.gray('Name')}: ${banner.name}`)
        }

        if (banner.published !== undefined) {
          console.log(`  ${chalk.gray('Published')}: ${banner.published ? chalk.green('Yes') : chalk.yellow('No')}`)
        }

        if (banner.schedules?.length) {
          console.log(`  ${chalk.gray('Schedules')}: ${banner.schedules.length}`)
        }

        if (banner.variants?.length) {
          console.log(`  ${chalk.gray('Variants')}: ${banner.variants.length}`)
        }

        console.log(chalk.gray('─'.repeat(80)))
      })

      console.log(chalk.green(`\n✓ Found ${banners.length} banner(s)`))
    } catch (error) {
      console.error(chalk.red(`Failed to list banners: ${error.message}`))
      if (error.response) {
        console.error(chalk.red(`Status: ${error.response.status}`))
        console.error(chalk.red(`Response: ${JSON.stringify(error.response.data)}`))
      }
      process.exit(1)
    }
  } catch (error) {
    console.error(chalk.red(`Failed to list banners: ${error.message}`))
    process.exit(1)
  }
}

module.exports = listBannersCommand
