import * as core from '@actions/core'
import * as k8s from '@kubernetes/client-node'
import * as fs from 'fs'
import * as path from 'path'
import { filter, clone } from 'lodash'
import { Cluster } from '@kubernetes/client-node'

interface Config {
  branch: string
  cluster: string
  namespace: string
  deployment: string
}

/**
 * The main function for the action.
 *
 * @returns Resolves when the action is complete.
 */
export async function run(): Promise<void> {
  try {
    //
    const configPath = core.getInput('config-path')
    console.log('configPath:', configPath)
    //
    const clusterPath = core.getInput('cluster-path')
    console.log('clusterPath:', clusterPath)
    //
    const deployImage: string = core.getInput('image')
    console.log('image:', deployImage)
    //
    const branch: string = String(process.env.GITHUB_REF_NAME)
    console.log('branch:', branch)
    //
    const workspace: string = String(process.env.GITHUB_WORKSPACE)
    console.log('workspace:', workspace)
    //
    const configJson = fs.readFileSync(path.join(workspace, configPath), 'utf8')
    console.log('configJson:', configJson)
    const deployConfigArr = JSON.parse(configJson) as Config[]
    console.log('deployConfigArr:', deployConfigArr)
    const filterDeployConfig = filter(deployConfigArr, { branch: branch })
    for (const deployConfig of filterDeployConfig) {
      console.log('deployConfig:', deployConfig)
      const kc = new k8s.KubeConfig()
      kc.loadFromFile(
        path.join(workspace, clusterPath + deployConfig.cluster + '.yaml')
      )
      const currentCluster: Cluster | null = kc.getCurrentCluster()
      console.log('old_cluster', currentCluster)
      if (currentCluster === null) {
        continue
      }
      kc.addCluster({
        name: currentCluster.server,
        server: currentCluster.server,
        caData: currentCluster.caData,
        skipTLSVerify: true,
        tlsServerName: '127.0.0.1'
      })
      console.log('now_cluster', kc.getCurrentCluster())
      const applyHttps = await kc.applyToHTTPSOptions({
        checkServerIdentity: () => undefined,
        rejectUnauthorized: false,
        servername: '127.0.0.1',
        host: '127.0.0.1'
      })
      console.log('disable ssl:', applyHttps)
      const k8sApi = kc.makeApiClient(k8s.AppsV1Api)
      const nowDeployment = await k8sApi.readNamespacedDeployment({
        name: deployConfig.deployment,
        namespace: deployConfig.namespace
      })
      console.log('nowDeployment:', nowDeployment)
      const deployment = clone(nowDeployment)
      if (deployment.spec === undefined) {
        console.log('deployment.spec is missing')
        continue
      }
      if (deployment.spec.template.spec === undefined) {
        console.log('deployment.spec.template.spec is missing')
        continue
      }
      if (deployment.spec.template.spec.containers.length === 0) {
        console.log('deployment.spec.template.spec.containers is zero')
        continue
      }
      deployment.spec.template.spec.containers[0].image = deployImage
      const deployRes =
        await k8s.KubernetesObjectApi.makeApiClient(kc).patch(nowDeployment)
      console.log('deployRes:', deployRes)
    }
  } catch (error) {
    // Fail the workflow run if an error occurs
    if (error instanceof Error) core.setFailed(error.message)
  }
}
