name: CD Deployment - Kubernetes

on:
  workflow_run:
    workflows: ["CD Bootstrap - Release Image Publish"]
    types: [completed]
    branches: [main, develop]
  workflow_dispatch:
    inputs:
      image_tag:
        description: 'Image tag to deploy (e.g., latest, dev)'
        required: true
        default: 'dev'
        type: string

jobs:
  deploy:
    name: Deploy to Kubernetes
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install kubectl
        run: |
          curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
          chmod +x kubectl
          sudo mv kubectl /usr/local/bin/

      - name: Install Kustomize
        run: |
          curl -Lo kustomize.tar.gz https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2Fv5.4.1/kustomize_v5.4.1_linux_amd64.tar.gz
          tar -xzf kustomize.tar.gz
          chmod +x kustomize
          sudo mv kustomize /usr/local/bin/

      - name: Set Image Tag
        run: |
          IMAGE_TAG="${{ github.event.inputs.image_tag }}"
          if [[ -z "$IMAGE_TAG" ]]; then
            IMAGE_TAG="dev" # Default for auto-trigger
          fi
          echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV

      - name: Kustomize Edit Image Tag
        working-directory: ./infra/k8s/overlays/dev
        run: |
          kustomize edit set image workclub-api=192.168.241.13:8080/workclub-api:$IMAGE_TAG
          kustomize edit set image workclub-frontend=192.168.241.13:8080/workclub-frontend:$IMAGE_TAG

      - name: Deploy to Kubernetes
        run: |
          set -euo pipefail
          export KUBECONFIG=$HOME/.kube/config
          mkdir -p $HOME/.kube
          if echo "${{ secrets.KUBECONFIG }}" | grep -q "apiVersion"; then
            echo "Detected plain text KUBECONFIG"
            printf '%s' "${{ secrets.KUBECONFIG }}" > $KUBECONFIG
          else
            echo "Detected base64 KUBECONFIG"
            # Handle potential newlines/wrapping in the secret
            printf '%s' "${{ secrets.KUBECONFIG }}" | base64 -d > $KUBECONFIG
          fi
          chmod 600 $KUBECONFIG

          kubectl --kubeconfig="$KUBECONFIG" config view >/dev/null
          
          # Diagnostics
          echo "Kubeconfig path: $KUBECONFIG"
          echo "Kubeconfig size: $(wc -c < $KUBECONFIG) bytes"
          echo "Available contexts:"
          kubectl --kubeconfig="$KUBECONFIG" config get-contexts
          
          if ! grep -q "current-context" $KUBECONFIG; then
            echo "Warning: current-context missing, attempting to fix..."
            FIRST_CONTEXT=$(kubectl --kubeconfig="$KUBECONFIG" config get-contexts -o name | head -n 1)
            if [ -n "$FIRST_CONTEXT" ]; then
              kubectl --kubeconfig="$KUBECONFIG" config use-context "$FIRST_CONTEXT"
            fi
          fi
          
          echo "Current context: $(kubectl --kubeconfig="$KUBECONFIG" config current-context)"
          
          # Ensure target namespace exists
          kubectl --kubeconfig="$KUBECONFIG" create namespace workclub-dev --dry-run=client -o yaml | kubectl --kubeconfig="$KUBECONFIG" apply -f -
          
          # Apply manifests (non-destructive by default; avoid DB state churn)
          kubectl --kubeconfig="$KUBECONFIG" config view --minify # Verification of context
          kustomize build --load-restrictor LoadRestrictionsNone infra/k8s/overlays/dev | kubectl --kubeconfig="$KUBECONFIG" apply -f -

          # Rollout verification
          kubectl --kubeconfig="$KUBECONFIG" rollout status statefulset/workclub-postgres -n workclub-dev --timeout=300s
          kubectl --kubeconfig="$KUBECONFIG" rollout status deployment/workclub-keycloak -n workclub-dev --timeout=600s
          kubectl --kubeconfig="$KUBECONFIG" rollout status deployment/workclub-api -n workclub-dev --timeout=300s
          kubectl --kubeconfig="$KUBECONFIG" rollout status deployment/workclub-frontend -n workclub-dev --timeout=300s
