name: CI

on:
  push:
    branches: [main]

jobs:
  build-and-start:
    runs-on: [ubuntu-latest, docker]
    container:
      image: node:20-bookworm
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Verify app starts
        run: |
          timeout 20 npm run start:prod || [ $? -eq 124 ]
        env:
          PORT: 4000

  deploy:
    needs: build-and-start
    runs-on: [ubuntu-latest, docker]
    container:
      image: node:20-bookworm
    steps:
      - name: Install Docker CLI
        run: |
          apt-get update -qq && apt-get install -y -qq ca-certificates curl
          install -m 0755 -d /etc/apt/keyrings
          curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
          chmod a644 /etc/apt/keyrings/docker.asc
          echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian bookworm stable" > /etc/apt/sources.list.d/docker.list
          apt-get update -qq && apt-get install -y -qq docker-ce-cli docker-compose-plugin
      - name: Checkout
        uses: actions/checkout@v4
      - name: Deploy with docker-compose
        run: docker compose -p docker-stack up -d --build backend
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}
          UPLOADS_PATH: ${{ secrets.UPLOADS_PATH }}
