variables:
  REGION: "us-west1"
  PROJECT_ID: $GCP_PROJECT_ID
  ARTIFACT_REGISTRY_HOSTNAME: "us-west1-docker.pkg.dev"
  ARTIFACT_REGISTRY_REPOSITORY: "$ARTIFACT_REGISTRY_HOSTNAME/$PROJECT_ID/images"
  TEMP_SERVICE_ACCOUNT_PATH: "/tmp/service-account-key.json"

.scripts: &scripts
  before_script:
    - export PATH="$CI_PROJECT_DIR/.local/bin:$PATH"
    - export PANTS_BASE="${CI_MERGE_REQUEST_DIFF_BASE_SHA:-$CI_COMMIT_BEFORE_SHA}"
    - echo $(base64 -d $GCP_SERVICE_ACCOUNT_KEY) > $TEMP_SERVICE_ACCOUNT_PATH
    - gcloud auth activate-service-account --key-file $TEMP_SERVICE_ACCOUNT_PATH
    - gcloud config set project $GCP_PROJECT_ID
    - gcloud auth configure-docker $ARTIFACT_REGISTRY_HOSTNAME
  after_script:
    - rm $TEMP_SERVICE_ACCOUNT_PATH

.build_pants_docker_images:
  stage: build
  script:
    - |
      # Declare an associative array to map app directories to service names
      declare -A SERVICES=(
        ["ingest/facilities"]="ingestion-service"
      )

      # changed_targets=$(pants --changed-since=$PANTS_BASE --changed-dependents=transitive list)

      # Loop through each service and build its Docker image if it has changed
      for APP_DIR in "${!SERVICES[@]}"; do
        SERVICE_NAME="${SERVICES[$APP_DIR]}"
        echo "Building Docker image for ${SERVICE_NAME}..."

        # Change into the service directory to build the Docker image
        pants package ::
        
        docker build -t $ARTIFACT_REGISTRY_REPOSITORY/${SERVICE_NAME}:$CI_COMMIT_SHORT_SHA .
        docker push $ARTIFACT_REGISTRY_REPOSITORY/${SERVICE_NAME}:$CI_COMMIT_SHORT_SHA
        
        # Return to the root project directory after building the Docker image
        cd -
      done
  artifacts:
    paths:
      - dist/  # Store any necessary build artifacts if needed
    expire_in: 1 week
  extends: .cache_template
  <<: 
    - *scripts

.deploy_to_gcp:
  stage: deploy
  script:
    - |
      # Declare the same associative array to map app directories to service names
      declare -A SERVICES=(
        ["ingest/facilities"]="ingestion-service"
      )

      # changed_targets=$(pants --changed-since=$PANTS_BASE --changed-dependents=transitive list)

      # Loop through each service and deploy it to GCP if it has changed
      for APP_DIR in "${!SERVICES[@]}"; do
        SERVICE_NAME="${SERVICES[$APP_DIR]}"
        echo "Deploying ${SERVICE_NAME} to GCP..."
        gcloud run deploy $SERVICE_NAME \
          --image $ARTIFACT_REGISTRY_REPOSITORY/${SERVICE_NAME}:$CI_COMMIT_SHORT_SHA \
          --region $REGION \
          --platform managed \
          --allow-unauthenticated
      done
  extends: .cache_template
  <<: 
    - *scripts
