name: Deploy

on:
  push:
    branches:
      - dev
      - develop
  workflow_dispatch:

jobs:
  deploy-dev:
    if: ${{ github.event_name == 'push' }}
    runs-on: ubuntu-latest
    container:
      volumes:
        - /docker/FlockPal-dev:/docker/FlockPal-dev
    steps:
      - name: Update dev checkout
        run: |
          set -e
          cd /docker/FlockPal-dev
          git fetch --all --prune
          git reset --hard "origin/${{ github.ref_name }}"
          git clean -fd

      - name: Validate backend
        run: |
          set -e
          cd /docker/FlockPal-dev
          docker run --rm -v "$PWD/backend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build && npm test"

      - name: Validate frontend
        run: |
          set -e
          cd /docker/FlockPal-dev
          docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"

      - name: Validate dev compose config
        run: |
          set -e
          cd /docker/FlockPal-dev
          docker compose -f docker-compose.dev.yaml config --quiet

      - name: Deploy dev
        run: |
          set -e
          cd /docker/FlockPal-dev
          docker compose -f docker-compose.dev.yaml up -d --build

  deploy-prod:
    if: ${{ github.event_name == 'workflow_dispatch' }}
    runs-on: ubuntu-latest
    container:
      volumes:
        - /docker/FlockPal:/docker/FlockPal
    steps:
      - name: Update prod checkout
        run: |
          set -e
          cd /docker/FlockPal
          git fetch --all --prune
          git reset --hard "origin/${{ github.ref_name }}"
          git clean -fd

      - name: Validate backend
        run: |
          set -e
          cd /docker/FlockPal
          docker run --rm -v "$PWD/backend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build && npm test"

      - name: Validate frontend
        run: |
          set -e
          cd /docker/FlockPal
          docker run --rm -v "$PWD/frontend:/src:ro" -w /tmp/app node:22-alpine sh -lc "cp -a /src/. /tmp/app && npm ci && npm run build"

      - name: Validate prod compose config
        run: |
          set -e
          cd /docker/FlockPal
          docker compose -f docker-compose.prod.yml config --quiet

      - name: Deploy prod
        run: |
          set -e
          cd /docker/FlockPal
          docker compose -f docker-compose.prod.yml up -d --build
