name: Build and Deploy BlaaAi

on:
  push:
    branches:
      - main
  workflow_dispatch:

env:
  SERVICE_NAME: blaaai

jobs:
  build-and-deploy:
    runs-on: debian-host

    env:
      PATH: /usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/sbin:/bin:/snap/bin
      DOCKER_HOST: unix:///var/run/docker.sock

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

      - name: Log in to Docker Registry
        run: |
          echo "${{ secrets.HARBOR_ROBOT_TOKEN }}" | docker login registry.i80.dk -u "robot\$gitserver" --password-stdin

      - name: Build Docker image
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker build \
            --build-arg BUILD_VERSION=${{ github.run_number }} \
            --build-arg GIT_COMMIT=$SHA \
            --build-arg BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ) \
            -t registry.i80.dk/gitea/${SERVICE_NAME}:latest \
            -t registry.i80.dk/gitea/${SERVICE_NAME}:$SHA .

      - name: Push Docker image
        run: |
          SHA=$(git rev-parse --short HEAD)
          docker push registry.i80.dk/gitea/${SERVICE_NAME}:latest
          docker push registry.i80.dk/gitea/${SERVICE_NAME}:$SHA

      - name: Deploy to Nomad
        run: |
          nomad job validate ${SERVICE_NAME}.nomad
          nomad job run ${SERVICE_NAME}.nomad
        env:
          NOMAD_ADDR: "https://nomad.i80.dk:4646"

      - name: Verify deployment
        run: |
          echo "Deployment triggered — checking status..."
          sleep 20
          nomad job status ${SERVICE_NAME}
        env:
          NOMAD_ADDR: "https://nomad.i80.dk:4646"

      - name: Health check
        run: |
          sleep 30
          curl -sf https://${SERVICE_NAME}.i80.dk/health && echo "Health check passed"
