name: Build and Deploy to k3s (Production)
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: '20'

      - name: Install dependencies
        run: npm ci

      - name: Build Next.js app
        run: npm run build
        env:
          NEXT_PUBLIC_API_URL: ${{ secrets.PROD_API_URL }}

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

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

      - name: Push Docker images
        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 }}" > ~/.kube/config
          chmod 600 ~/.kube/config

      - name: Validate kubeconfig and cluster connectivity
        run: |
          if ! kubectl version --client; then
            echo "❌ Failed to get kubectl version"
            exit 1
          fi
          if ! kubectl cluster-info --kubeconfig ~/.kube/config > /dev/null 2>&1; then
            echo "❌ Failed to connect to cluster"
            exit 1
          fi
          echo "✅ Successfully connected to Kubernetes cluster"

      - name: Deploy to Production (k3s)
        run: |
          echo "Applying Kubernetes manifests..."
          kubectl apply -k deploy/k3s/prod --kubeconfig ~/.kube/config

          echo "Updating deployment image..."
          kubectl set image deployment/hosting-frontend \
            hosting-frontend=${{ secrets.REGISTRY_URL }}/${{ secrets.REGISTRY_USER }}/hosting-frontend-prod:${{ github.sha }} \
            -n hosting --kubeconfig ~/.kube/config

          echo "Waiting for rollout to complete..."
          kubectl rollout status deployment/hosting-frontend -n hosting --kubeconfig ~/.kube/config --timeout=5m

          echo "✅ Production deployment complete!"
