name: Build and Deploy to k3s
on:
  push:
    tags:
      - 'PROD*'

jobs:
  build-and-deploy:
    env:
      KUBECONFIG: ~/.kube/config
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '22'


      - name: Install dependencies
        run: npm ci

      - name: Build Angular app
        run: npm run build --prod

      - name: Build Docker image
        run: |
          docker build -t ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:${{ github.sha }} .
          docker tag ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:${{ github.sha }} ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:latest

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

      - name: Push Docker image
        run: |
          docker push ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:${{ github.sha }}
          docker push ${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:latest

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

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


      - name: Validate kubeconfig
        run: |
          if ! kubectl version --client && kubectl cluster-info --kubeconfig ~/.kube/config; then
            echo "❌ Failed to connect to cluster"
            exit 1
          fi


      - name: Deploy to k3s
        run: |
          kubectl apply -k deploy/k3s/prod --kubeconfig ~/.kube/config
          kubectl set image deployment/hosting-frontend \
            hosting-frontend=${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:${{ github.sha }} \
            -n hosting --kubeconfig ~/.kube/config
          kubectl rollout status deployment/hosting-frontend -n hosting --kubeconfig ~/.kube/config
