const chalk = require('chalk')
const { getConfig } = require('../lib/config')
const { getApps, getWebs } = require('../lib/api')
const { logHttpErrorDetails } = require('../lib/errors')

async function listAppsCommand() {
  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)
    }

    console.log(chalk.blue('Fetching apps and websites...\n'))

    try {
      // Get apps (React Native)
      const apps = await getApps()
      
      // Get websites (React/Next.js)
      const webs = await getWebs()

      const allItems = []
      
      // Process apps
      if (Array.isArray(apps)) {
        apps.forEach((app) => {
          allItems.push({
            id: app.id || app,
            name: app.name || 'N/A',
            description: app.description,
            type: 'App',
            typeLabel: chalk.blue('App'),
          })
        })
      } else if (apps && typeof apps === 'object') {
        Object.entries(apps).forEach(([id, app]) => {
          if (typeof app === 'object' && app !== null) {
            allItems.push({
              id: app.id || id,
              name: app.name || 'N/A',
              description: app.description,
              type: 'App',
              typeLabel: chalk.blue('App'),
            })
          }
        })
      }

      // Process websites
      if (Array.isArray(webs)) {
        webs.forEach((web) => {
          allItems.push({
            id: web.id || web,
            name: web.name || 'N/A',
            description: web.description,
            type: 'Website',
            typeLabel: chalk.green('Website'),
          })
        })
      } else if (webs && typeof webs === 'object') {
        Object.entries(webs).forEach(([id, web]) => {
          if (typeof web === 'object' && web !== null) {
            allItems.push({
              id: web.id || id,
              name: web.name || 'N/A',
              description: web.description,
              type: 'Website',
              typeLabel: chalk.green('Website'),
            })
          }
        })
      }

      if (allItems.length === 0) {
        console.log(chalk.yellow('No apps or websites found.'))
        return
      }

      console.log(chalk.bold('Apps and Websites:\n'))
      console.log(chalk.gray('─'.repeat(80)))

      allItems.forEach((item) => {
        console.log(`${item.typeLabel} ${chalk.bold(item.id)}`)
        console.log(`  Name: ${item.name}`)
        if (item.description) {
          console.log(`  Description: ${item.description}`)
        }
        console.log(`  Type: ${item.type}`)
        console.log(chalk.gray('─'.repeat(80)))
      })

      console.log(chalk.green(`\n✓ Found ${allItems.length} app(s)/website(s)`))
    } catch (error) {
      console.error(chalk.red(`Failed to list apps: ${error.message}`))
      logHttpErrorDetails(error)
      const st = error.name === 'APIError' ? error.status : error.response?.status
      if (st === 404) {
        console.error(chalk.yellow('\nTip: 404 usually means cmsUrl is wrong. It should point to your BILDIT CMS host.'))
        console.error(chalk.gray('  - Typical CMS URL: https://YOUR_PROJECT.web.app'))
        console.error(chalk.gray('  - Try: bild login https://YOUR_CMS_URL'))
      }
      process.exit(1)
    }
  } catch (error) {
    console.error(chalk.red(`Failed to list apps: ${error.message}`))
    process.exit(1)
  }
}

module.exports = listAppsCommand
