name: beancrate-ci

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

env:
  NODE_VERSION: "22"
  DATABASE_URL: postgres://beancrate:beancrate@localhost:5432/beancrate_test
  REDIS_URL: redis://localhost:6379/0

jobs:
  test:
    name: Test API and Web
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: beancrate
          POSTGRES_PASSWORD: beancrate
          POSTGRES_DB: beancrate_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U beancrate"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

      redis:
        image: redis:7
        ports:
          - 6379:6379

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

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

      - name: Install dependencies
        run: npm ci

      - name: Run database migrations
        run: npm run db:migrate

      - name: Lint
        run: npm run lint

      - name: Run tests
        run: npm test

      - name: Build application
        run: npm run build

  deploy:
    name: Deploy Production
    runs-on: ubuntu-latest
    needs: test
    if: github.ref == 'refs/heads/main'

    environment:
      name: production
      url: https://app.beancrate.example

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Deploy to production
        run: ./scripts/deploy.sh production
        env:
          DEPLOY_TOKEN: ${{ secrets.PRODUCTION_DEPLOY_TOKEN }}
          STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }}
          ROASTER_API_KEY: ${{ secrets.ROASTER_API_KEY }}