name: Deploy Development

on:
  push:
    branches:
      - dev
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    container:
      image: catthehacker/ubuntu:act-latest

    steps:
      - name: Checkout code
        shell: sh
        run: |
          git clone $GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git /workspace/repo
          cd /workspace/repo
          git checkout $GITHUB_REF_NAME

      - name: Build Docker image
        shell: sh
        run: |
          cd /workspace/repo
          docker build -t crew_admin:dev .
          docker save crew_admin:dev | gzip > crew_admin_dev.tar.gz

      - name: Setup SSH
        shell: sh
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
        run: |
          mkdir -p ~/.ssh
          chmod 700 ~/.ssh
          echo "$DEPLOY_SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts

      - name: Upload image and compose
        shell: sh
        env:
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
        run: |
          scp -i ~/.ssh/id_ed25519 \
            /workspace/repo/crew_admin_dev.tar.gz \
            /workspace/repo/docker-compose.dev.yml \
            ${DEPLOY_USER}@${DEPLOY_HOST}:/tmp/

      - name: Deploy on server
        shell: sh
        env:
          DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}

        run: |
          ssh -i ~/.ssh/id_ed25519 $DEPLOY_USER@$DEPLOY_HOST << 'EOF'
            set -e

            DEPLOY_DIR="/var/www/apps/crew_admin_dev"
            mkdir -p "$DEPLOY_DIR"

            echo "Loading image"
            docker load < /tmp/crew_admin_dev.tar.gz

            echo "Removing old crew_admin images"
            docker images | grep crew_admin | grep -v "$(docker images crew_admin:dev -q)" | awk '{print $3}' | xargs -r docker rmi -f || true

            echo "Updating compose file"
            cp /tmp/docker-compose.dev.yml "$DEPLOY_DIR/docker-compose.yml"

            cd "$DEPLOY_DIR"

            echo "Checking .env file"
            if [ ! -f .env ]; then
              echo ".env file not found at $DEPLOY_DIR/.env"
              echo "Please create it first with required variables:"
              echo "  - DB_*, IMAGES_DIRECTORY, PRODUCTION_PRIVATE_SERVER"
              exit 1
            fi

            echo "Fixing .env permissions"
            sudo chown $USER:$USER .env
            sudo chmod 600 .env

            echo "Ensure networks"
            docker network inspect traefik-public >/dev/null 2>&1 || \
              docker network create traefik-public
            docker network inspect crew-app-net >/dev/null 2>&1 || \
              docker network create crew-app-net

            echo "Starting containers (env vars from .env file)"
            docker compose up -d

            echo "Waiting for app container"
            sleep 15

            if docker ps --format '{{.Names}}' | grep -q crew_admin_app; then
              echo "Clearing and rebuilding config cache"
              docker compose exec -T app php artisan config:clear
              docker compose exec -T app php artisan config:cache
            else
              echo "App container not running"
              docker compose logs
              exit 1
            fi

            echo "Cleanup"
            rm -f /tmp/crew_admin_dev.tar.gz /tmp/docker-compose.dev.yml
            
            echo "Aggressive Docker cleanup to reclaim space"
            docker image prune -af --filter "until=24h" || true
            docker container prune -f || true
            docker volume prune -f || true
            docker builder prune -af --filter "until=48h" || true
            echo "Docker space usage:"
            docker system df

            echo "Deployment completed"
          EOF


      - name: Health check
        shell: sh
        run: |
          echo "Waiting for app to be ready..."
          sleep 20
          
          echo "Testing health check (ignoring SSL cert for now)..."
          HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" --max-time 30 https://dev-admin.crewsportswear.app || echo "000")
          
          if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "302" ] || [ "$HTTP_CODE" = "301" ]; then
            echo "Health check passed! (HTTP $HTTP_CODE)"
            echo "Note: Using -k to ignore SSL cert. Check Traefik logs if cert not ready."
          else
            echo "Health check failed! (HTTP $HTTP_CODE)"
            echo ""
            echo "Troubleshooting:"
            echo "  1. Check if container is running:"
            echo "     docker ps | grep crew_admin_app"
            echo "  2. Check container logs:"
            echo "     docker logs crew_admin_app_dev"
            echo "  3. Check Traefik routing:"
            echo "     docker logs traefik 2>&1 | grep crew-admin"
            echo "  4. Verify network connectivity:"
            echo "     docker network inspect traefik-public"
            exit 1
          fi
