import color from 'kleur'
import { del, get, handleError, post } from '../http'
import { resolveAppName } from '../name'

interface EnvVar {
  key: string
  value: string
}

export async function envList(name: string | undefined) {
  const appName = resolveAppName(name)
  if (!appName) return

  const vars = await get<EnvVar[]>(`/api/apps/${appName}/env`)
  if (!vars) {
    console.error(`App not found: ${appName}`)
    return
  }

  console.log(color.bold().cyan(`Environment Variables for ${appName}`))
  console.log()

  if (vars.length === 0) {
    console.log(color.gray('  No environment variables set'))
    return
  }

  for (const v of vars) {
    console.log(`  ${color.bold(v.key)}=${color.gray(v.value)}`)
  }
}

export async function envSet(name: string | undefined, keyOrKeyValue: string, valueArg?: string) {
  let key: string
  let value: string

  if (valueArg !== undefined) {
    // KEY value format
    key = keyOrKeyValue.trim()
    value = valueArg
  } else {
    // KEY=value format
    const eqIndex = keyOrKeyValue.indexOf('=')
    if (eqIndex === -1) {
      console.error('Invalid format. Use: KEY value or KEY=value')
      return
    }
    key = keyOrKeyValue.slice(0, eqIndex).trim()
    value = keyOrKeyValue.slice(eqIndex + 1)
  }

  if (!key) {
    console.error('Key cannot be empty')
    return
  }

  const appName = resolveAppName(name)
  if (!appName) return

  try {
    const result = await post<{ ok: boolean, error?: string }>(`/api/apps/${appName}/env`, { key, value })
    if (result?.ok) {
      console.log(color.green(`Set ${color.bold(key.toUpperCase())} for ${appName}`))
      console.log(color.gray('App restarted to apply changes'))
    } else {
      console.error(result?.error ?? 'Failed to set variable')
    }
  } catch (error) {
    handleError(error)
  }
}

export async function envRm(name: string | undefined, key: string) {
  if (!key) {
    console.error('Key is required')
    return
  }

  const appName = resolveAppName(name)
  if (!appName) return

  const ok = await del(`/api/apps/${appName}/env/${key.toUpperCase()}`)
  if (ok) {
    console.log(color.green(`Removed ${color.bold(key.toUpperCase())} from ${appName}`))
    console.log(color.gray('App restarted to apply changes'))
  }
}
