/**
 * ArgoCD API Client
 * Handles communication with ArgoCD for GitOps status and management
 */

import axios, { AxiosInstance } from 'axios'

export interface ArgoCDApplication {
  metadata: {
    name: string
    namespace: string
    uid: string
  }
  spec: {
    project: string
    source: {
      repoURL: string
      path?: string
      targetRevision?: string
    }
    destination: {
      server: string
      namespace: string
    }
    syncPolicy?: {
      automated?: {
        prune: boolean
        selfHeal: boolean
      }
      syncOptions?: string[]
    }
  }
  status: {
    health: {
      status: 'Healthy' | 'Degraded' | 'Progressing' | 'Suspended' | 'Missing' | 'Unknown'
      message?: string
    }
    sync: {
      status: 'Synced' | 'OutOfSync' | 'Unknown'
      revision?: string
    }
    conditions?: Array<{
      type: string
      message: string
      lastTransitionTime: string
    }>
  }
}

export interface ArgoCDSyncResult {
  resources: Array<{
    kind: string
    namespace: string
    name: string
    status: string
    message?: string
  }>
}

class ArgoCDClient {
  private client: AxiosInstance
  private baseURL: string

  constructor(accessToken?: string) {
    this.baseURL = process.env.NEXT_PUBLIC_ARGOCD_URL || 'http://localhost:8080'
    
    this.client = axios.create({
      baseURL: this.baseURL,
      headers: {
        'Content-Type': 'application/json',
        ...(accessToken && { Authorization: `Bearer ${accessToken}` }),
      },
    })
  }

  /**
   * Get all ArgoCD applications
   */
  async getApplications(): Promise<ArgoCDApplication[]> {
    try {
      const response = await this.client.get('/api/v1/applications')
      return response.data.items || []
    } catch (error: any) {
      console.error('Failed to fetch ArgoCD applications:', error)
      throw new Error(`Failed to fetch applications: ${error.message}`)
    }
  }

  /**
   * Get a specific ArgoCD application
   */
  async getApplication(name: string, namespace: string = 'argocd'): Promise<ArgoCDApplication> {
    try {
      const response = await this.client.get(`/api/v1/applications/${name}`, {
        params: { namespace },
      })
      return response.data
    } catch (error: any) {
      console.error(`Failed to fetch ArgoCD application ${name}:`, error)
      throw new Error(`Failed to fetch application: ${error.message}`)
    }
  }

  /**
   * Sync an ArgoCD application
   */
  async syncApplication(
    name: string,
    namespace: string = 'argocd',
    prune: boolean = false,
    dryRun: boolean = false
  ): Promise<ArgoCDSyncResult> {
    try {
      const response = await this.client.post(
        `/api/v1/applications/${name}/sync`,
        {
          prune,
          dryRun,
        },
        {
          params: { namespace },
        }
      )
      return response.data
    } catch (error: any) {
      console.error(`Failed to sync ArgoCD application ${name}:`, error)
      throw new Error(`Failed to sync application: ${error.message}`)
    }
  }

  /**
   * Get application logs
   */
  async getApplicationLogs(
    name: string,
    namespace: string = 'argocd',
    tailLines: number = 100
  ): Promise<string[]> {
    try {
      const response = await this.client.get(`/api/v1/applications/${name}/logs`, {
        params: {
          namespace,
          tailLines,
        },
      })
      return response.data.logs || []
    } catch (error: any) {
      console.error(`Failed to fetch logs for ${name}:`, error)
      throw new Error(`Failed to fetch logs: ${error.message}`)
    }
  }

  /**
   * Get application resource tree
   */
  async getApplicationResourceTree(
    name: string,
    namespace: string = 'argocd'
  ): Promise<any> {
    try {
      const response = await this.client.get(`/api/v1/applications/${name}/resource-tree`, {
        params: { namespace },
      })
      return response.data
    } catch (error: any) {
      console.error(`Failed to fetch resource tree for ${name}:`, error)
      throw new Error(`Failed to fetch resource tree: ${error.message}`)
    }
  }
}

export function createArgoCDClient(accessToken?: string): ArgoCDClient {
  return new ArgoCDClient(accessToken)
}

