name: Create and publish backend image

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      tags:
        description: 'Docker image tag (e.g: v0.0.1)'
        required: false
        type: string

env:
  IMAGE_NAME: cohere-toolkit-backend

jobs:
  build-and-push-backend-image:
    runs-on: ubuntu-latest
    permissions:
      contents: read

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

      - name: Authenticate with service account
        uses: google-github-actions/auth@v1
        with:
          credentials_json: ${{ secrets.GCP_SA_KEY }}

      - name: Login
        uses: google-github-actions/setup-gcloud@v1

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v1
        with:
          project_id: ${{ vars.GCP_PROJECT_ID }}
          export_default_credentials: true

      - name: Configure Docker
        run: yes | gcloud auth configure-docker us-docker.pkg.dev

      # - name: Checkout repository
      #   uses: actions/checkout@v2

      # - name: Extract metadata (tags, labels) for Docker
      #   id: meta
      #   uses: docker/metadata-action@v3
      #   with:
      #     images: ${{ vars.REGISTRY }}/${{ env.IMAGE_NAME }}

      # - name: Build Docker image
      #   run: |
      #     docker build -t ${{ env.IMAGE_NAME }} -f ./src/backend/Dockerfile .

      - name: Pull docker hello-world image
        run: docker pull hello-world

      - name: Tag Docker image
        run: |
          docker tag hello-world  ${{ vars.REGISTRY }}/hello-world

      # Save the SA key to a file so that it can be used by the docker build
      - name: Save SA key to file
        run: echo "${{ secrets.GCP_SA_KEY }}" > /tmp/gcp_sa_key.json

      - name: Try auth again!
        run: |
          gcloud auth activate-service-account --key-file /tmp/gcp_sa_key.json
          gcloud auth configure-docker us-docker.pkg.dev
          docker login -u _json_key -p "$(cat /tmp/gcp_sa_key.json)" https://gcrc.io

      - name: Push Docker image
        run: |
          gcloud auth configure-docker --quiet && \



          docker push ${{ vars.REGISTRY }}/hello-world

      # - name: Tag Docker image
      #   run: |
      #     docker tag ${{ env.IMAGE_NAME }} ${{ steps.meta.outputs.tags }}

      # - name: Push Docker image
      #   env:
      #     THE_TAGS: ${{ steps.meta.outputs.tags }}
      #   run: |
      #     docker push ${{ steps.meta.outputs.tags }}