name: Deploy

on:
  push:
    branches: [main]
  release:
    types: [published]

env:
  NODE_VERSION: '18'

jobs:
  deploy-staging:
    name: Deploy to Staging
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    environment: staging
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build
        env:
          NODE_ENV: production

      - name: Run migrations
        run: npm run db:push
        env:
          DATABASE_URL: ${{ secrets.STAGING_DATABASE_URL }}

      - name: Deploy to staging
        run: echo "Deploying to staging environment"
        env:
          AWS_REGION: ${{ secrets.AWS_REGION }}
          STAGING_API_KEY: ${{ secrets.STAGING_API_KEY }}

  deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-latest
    if: github.event_name == 'release'
    environment: production
    needs: [deploy-staging]
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ env.NODE_VERSION }}
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build
        env:
          NODE_ENV: production

      - name: Run migrations
        run: npm run db:push
        env:
          DATABASE_URL: ${{ secrets.PRODUCTION_DATABASE_URL }}

      - name: Deploy to production
        run: echo "Deploying to production environment"
        env:
          AWS_REGION: ${{ secrets.AWS_REGION }}
          PRODUCTION_API_KEY: ${{ secrets.PRODUCTION_API_KEY }}
