name: 'Teardown Deploy Namespace'
description: 'Clean up Dynamo platform resources and delete the Kubernetes namespace'

inputs:
  kubeconfig_base64:
    description: 'Base64-encoded kubeconfig for cluster access'
    required: true
  namespace:
    description: 'Namespace to tear down'
    required: true

runs:
  using: "composite"
  steps:
    - name: Setup Kubeconfig
      shell: bash
      run: |
        echo "${{ inputs.kubeconfig_base64 }}" | base64 -d > ${{ github.workspace }}/.kubeconfig
        chmod 600 ${{ github.workspace }}/.kubeconfig
        echo "KUBECONFIG=${{ github.workspace }}/.kubeconfig" >> $GITHUB_ENV

    - name: Debug - List resources
      shell: bash
      env:
        NAMESPACE: ${{ inputs.namespace }}
      run: |
        echo "::group::List resources in namespace $NAMESPACE"
        kubectl get dynamographdeployments -n $NAMESPACE || true
        kubectl get all -n $NAMESPACE || true
        echo "::endgroup::"

    - name: Delete stale DynamoGraphDeployments
      shell: bash
      env:
        NAMESPACE: ${{ inputs.namespace }}
      run: |
        echo "::group::Delete stale DynamoGraphDeployments"
        kubectl delete dynamographdeployments --all -n $NAMESPACE --timeout=60s
        echo "::endgroup::"

    - name: Uninstall Helm chart
      shell: bash
      env:
        NAMESPACE: ${{ inputs.namespace }}
      run: |
        echo "::group::Uninstall Helm chart"
        if helm status dynamo-platform --namespace $NAMESPACE &>/dev/null; then
          helm uninstall dynamo-platform --namespace $NAMESPACE --timeout 10m
        else
          echo "Helm release dynamo-platform not found, skipping"
        fi
        echo "::endgroup::"

    - name: Delete namespace
      shell: bash
      env:
        NAMESPACE: ${{ inputs.namespace }}
      run: |
        echo "::group::Delete namespace $NAMESPACE"
        kubectl delete namespace $NAMESPACE --timeout=120s
        echo "::endgroup::"
