name: Build and Deploy SQDC Dashboard

on:
  push:
    branches:
      - '**'
  pull_request:
    branches:
      - '**'

env:
  REGISTRY_URL: ${{ secrets.REGISTRY_URL }}
  REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
  REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
  IMAGE_TAG: ${{ github.sha }}

jobs:
  build:
    name: Build Docker Image
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: dashboard-sqdc
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: '18'
          cache: 'npm'
          cache-dependency-path: dashboard-sqdc/package-lock.json

      - run: npm ci

      - run: npm run build

      - uses: docker/setup-buildx-action@v2

      - name: Login to Container Registry
        run: echo "$REGISTRY_PASSWORD" | docker login "$REGISTRY_URL" -u "$REGISTRY_USER" --password-stdin

      - name: Build and Push Docker image
        run: |
          docker build -t "$REGISTRY_URL/sortifal/pfee:$IMAGE_TAG" -t "$REGISTRY_URL/sortifal/pfee:latest" .
          docker push "$REGISTRY_URL/sortifal/pfee:$IMAGE_TAG"
          docker push "$REGISTRY_URL/sortifal/pfee:latest"

  deploy:
    name: Deploy to Kubernetes
    runs-on: ubuntu-latest
    needs: build
    if: github.event_name == 'push'
    defaults:
      run:
        working-directory: dashboard-sqdc
    steps:
      - uses: actions/checkout@v3

      - uses: azure/setup-kubectl@v3
        with:
          version: 'latest'

      - name: Configure kubectl
        run: |
          mkdir -p $HOME/.kube
          echo "${{ secrets.KUBE_CONFIG }}" > $HOME/.kube/config
          chmod 600 $HOME/.kube/config

      - name: Create registry credentials
        run: |
          kubectl create secret docker-registry registry-credentials \
            --docker-server="$REGISTRY_URL" \
            --docker-username="$REGISTRY_USER" \
            --docker-password="$REGISTRY_PASSWORD" \
            -n sqdc-dashboard \
            --dry-run=client -o yaml | kubectl apply -f -

      - name: Deploy to Kubernetes
        run: |
          kubectl apply -f k8s/namespace.yaml k8s/deployment.yaml k8s/service.yaml k8s/ingress.yaml

      - name: Update deployment and verify
        run: |
          kubectl set image deployment/sqdc-dashboard dashboard="$REGISTRY_URL/sortifal/pfee:$IMAGE_TAG" -n sqdc-dashboard
          kubectl rollout status deployment/sqdc-dashboard -n sqdc-dashboard --timeout=5m
          kubectl get pods,svc,ingress -n sqdc-dashboard
