/**
 * Docker Cleanup Command
 * Clean up unused containers, images, and volumes
 */

import { exec } from 'child_process'
import { promisify } from 'util'

const execAsync = promisify(exec)

export interface CleanupOptions {
  containers?: boolean
  images?: boolean
  volumes?: boolean
  networks?: boolean
  all?: boolean
}

export async function handle(args: CleanupOptions, context: any): Promise<string> {
  const {
    containers = true,
    images = true,
    volumes = false,
    networks = false,
    all = false
  } = args

  const results: string[] = []

  try {
    if (all || containers) {
      results.push('Cleaning up stopped containers...')
      const { stdout: containerOutput } = await execAsync('docker container prune -f')
      results.push(containerOutput)
    }

    if (all || images) {
      results.push('\nCleaning up dangling images...')
      const { stdout: imageOutput } = await execAsync('docker image prune -a -f')
      results.push(imageOutput)
    }

    if (all || volumes) {
      results.push('\nCleaning up unused volumes...')
      const { stdout: volumeOutput } = await execAsync('docker volume prune -f')
      results.push(volumeOutput)
    }

    if (all || networks) {
      results.push('\nCleaning up unused networks...')
      const { stdout: networkOutput } = await execAsync('docker network prune -f')
      results.push(networkOutput)
    }

    results.push('\n✓ Docker cleanup complete!')

    return results.join('\n')
  } catch (error: any) {
    throw new Error(`Docker cleanup failed: ${error.message}`)
  }
}

export default { handle }
