name: Deploy to Production

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: production
    steps:
      - uses: actions/checkout@v4
      
      - name: Setup PNPM
        uses: pnpm/action-setup@v2
        with:
          version: 8
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '25'
          cache: 'pnpm'
      
      - name: Install dependencies
        run: pnpm install --frozen-lockfile
      
      - name: Run database migrations
        run: |
          cd services/iam-service
          pnpm prisma generate
          pnpm prisma migrate deploy
        env:
          DATABASE_URL: ${{ secrets.NEON_DATABASE_URL_PRODUCTION }}
      
      - name: Setup kubectl
        uses: azure/setup-kubectl@v3
      
      - name: Configure kubectl
        run: |
          echo "${{ secrets.KUBECONFIG_PRODUCTION }}" | base64 -d > kubeconfig
          export KUBECONFIG=./kubeconfig
      
      - name: Deploy IAM Service
        run: |
          export KUBECONFIG=./kubeconfig
          kubectl apply -f deployments/production/kubernetes/iam-service.yaml
          kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml
          kubectl apply -f deployments/production/kubernetes/ingress.yaml
          kubectl rollout status deployment/iam-service -n production
      
      - name: Deploy Web App
        run: |
          export KUBECONFIG=./kubeconfig
          kubectl apply -f deployments/production/kubernetes/web-app.yaml || echo "Web app deployment not configured"
          kubectl rollout status deployment/web-app -n production || echo "Web app deployment not configured"
