name: CI

on:
  pull_request:
    branches: [main]
  workflow_dispatch:

jobs:
  ci:
    runs-on: ubuntu-latest

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

      - name: Install Bun
        run: |
          curl -fsSL https://bun.sh/install | bash
          echo "$HOME/.bun/bin" >> $GITHUB_PATH

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Lint
        run: bun run lint

      - name: Test
        run: bun run test

  e2e:
    runs-on: ubuntu-latest
    needs: ci
    env:
      DOCKER_HOST: tcp://localhost:2375

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

      - name: Start services
        run: |
          docker run -d --name postgres \
            -e POSTGRES_USER=lunarfront \
            -e POSTGRES_PASSWORD=lunarfront \
            -e POSTGRES_DB=postgres \
            -p 5432:5432 \
            postgres:16
          docker run -d --name valkey \
            -p 6379:6379 \
            valkey/valkey:8
          until docker exec postgres pg_isready -U lunarfront; do sleep 1; done
          until docker exec valkey valkey-cli ping; do sleep 1; done

      - name: Install Bun
        run: |
          curl -fsSL https://bun.sh/install | bash
          echo "$HOME/.bun/bin" >> $GITHUB_PATH

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Run API tests
        working-directory: packages/backend
        run: bun run api-test

      - name: Stop services
        if: always()
        run: |
          docker stop postgres valkey || true
          docker rm postgres valkey || true
