steps:
  # Build the container image
  - name: 'gcr.io/cloud-builders/docker'
    id: 'build'
    args:
      - 'build'
      - '-t'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:$BUILD_ID'
      - '--cache-from'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:latest'
      - '--build-arg'
      - 'NODE_ENV=production'
      - '-f'
      - 'website/server/Dockerfile'
      - 'website/server'

  # Push the container image
  - name: 'gcr.io/cloud-builders/docker'
    id: 'push'
    args:
      - 'push'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:$BUILD_ID'

  # Deploy to Cloud Run
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    id: 'deploy'
    entrypoint: 'gcloud'
    args:
      - 'run'
      - 'deploy'
      - '$_SERVICE_NAME'
      - '--image'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:$BUILD_ID'
      - '--region'
      - '$_REGION'
      - '--platform'
      - 'managed'
      - '--port'
      - '8080'
      - '--memory'
      - '1024Mi'
      - '--cpu'
      - '2'
      - '--min-instances'
      - '0'
      - '--max-instances'
      - '10'
      - '--timeout'
      - '35s'
      - '--ingress'
      - 'all'
      - '--allow-unauthenticated'
      - '--set-env-vars'
      - 'NODE_ENV=production'
      - '--set-secrets'
      - 'UPSTASH_REDIS_REST_URL=upstash-redis-rest-url:latest,UPSTASH_REDIS_REST_TOKEN=upstash-redis-rest-token:latest,CLOUDFLARE_ORIGIN_SECRET=cloudflare-origin-secret:latest,TURNSTILE_SECRET_KEY=turnstile-secret-key:latest'

  # Tag the image as latest
  - name: 'gcr.io/cloud-builders/docker'
    id: 'tag-latest'
    args:
      - 'tag'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:$BUILD_ID'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:latest'

  # Push the latest tag
  - name: 'gcr.io/cloud-builders/docker'
    id: 'push-latest'
    args:
      - 'push'
      - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:latest'

substitutions:
  _REGION: us-central1
  _SERVICE_NAME: repomix-server-us

options:
  logging: CLOUD_LOGGING_ONLY
  dynamic_substitutions: true

images:
  - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:$BUILD_ID'
  - '$_REGION-docker.pkg.dev/$PROJECT_ID/repomix/server:latest'
