name: Build and Deploy

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: docker
    steps:
      - name: Install tools
        run: apt-get update && apt-get install -y docker.io openssh-client

      - name: Checkout code
        uses: https://data.forgejo.org/actions/checkout@v4

      - name: Login to registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login git.lilastudy.com -u "${{ secrets.REGISTRY_USER }}" --password-stdin

      - name: Build API image
        run: |
          docker build \
            -t git.lilastudy.com/forgejo-lila/lila-api:latest \
            --target runner \
            -f apps/api/Dockerfile .

      - name: Build Web image
        run: |
          docker build \
            -t git.lilastudy.com/forgejo-lila/lila-web:latest \
            --target production \
            --build-arg VITE_API_URL=https://api.lilastudy.com \
            -f apps/web/Dockerfile .

      - name: Push images
        run: |
          docker push git.lilastudy.com/forgejo-lila/lila-api:latest
          docker push git.lilastudy.com/forgejo-lila/lila-web:latest

      - name: Deploy via SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh -o StrictHostKeyChecking=no ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} \
            "cd ~/lila-app && docker compose pull api web && docker compose up -d api web && docker image prune -f"
