name: Docker Build and Publish

on:
  push:
    branches:
      - dev

env:
  DOCKERHUB_SERVER_REPO: lamassu/lamassu-server
  DOCKERHUB_ADMIN_REPO: lamassu/lamassu-admin-server

jobs:
  build-and-publish:
    runs-on: ubuntu-22.04

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

      - name: Setup Turbo cache
        uses: actions/cache@v4
        with:
          path: .turbo
          key: ${{ runner.os }}-turbo-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-turbo-

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10.11.0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'pnpm'

      - name: Install dependencies
        run: pnpm install

      - name: Build packages with Turbo
        run: pnpm run build

      - name: Verify build artifacts
        run: |
          echo "=== Verifying typesafe-db build ==="
          ls -la packages/typesafe-db/lib/
          echo "=== Verifying admin-ui build ==="
          ls -la packages/admin-ui/build/

      - name: Package production build
        run: |
          # Create production-ready server package using pnpm deploy
          pnpm deploy --filter=./packages/server --prod lamassu-server --legacy
          
          # Copy built admin UI to public directory
          cp -r packages/admin-ui/build lamassu-server/public
          
          # Copy Dockerfile to lamassu-server context
          cp build/server.Dockerfile lamassu-server/
          
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_HUB_USERNAME }}
          password: ${{ secrets.DOCKER_HUB_TOKEN }}

      - name: Build and push server image
        uses: docker/build-push-action@v5
        with:
          context: lamassu-server
          push: true
          target: l-s
          file: lamassu-server/server.Dockerfile
          tags: ${{ env.DOCKERHUB_SERVER_REPO }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Build and push admin server image
        uses: docker/build-push-action@v5
        with:
          context: lamassu-server
          push: true
          target: l-a-s
          file: lamassu-server/server.Dockerfile
          tags: ${{ env.DOCKERHUB_ADMIN_REPO }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max
