steps:
  # Build Docker image
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'build'
      - '--target=runner'
      - '-t'
      - 'asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api:$BUILD_ID'
      - '-t'
      - 'asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api:latest'
      - './management-api'
    id: 'build-image'

  # Push to Artifact Registry
  - name: 'gcr.io/cloud-builders/docker'
    args:
      - 'push'
      - '--all-tags'
      - 'asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api'
    id: 'push-image'

  # Deploy to Cloud Run
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: gcloud
    args:
      - 'run'
      - 'deploy'
      - '${_SERVICE_NAME}'
      - '--image=asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api:$BUILD_ID'
      - '--region=${_REGION}'
      - '--platform=managed'
      - '--allow-unauthenticated'
      - '--service-account=907324191702-compute@developer.gserviceaccount.com'
      - '--set-secrets=JWT_SECRET=jwt-secret-dev-ydm-c360-manage:latest,FIREBASE_DATABASE_URL=firebase-database-url:latest'
      - '--set-env-vars=NODE_ENV=production,CORS_ORIGIN=${_CORS_ORIGIN}'
      - '--port=8080'
      - '--memory=1Gi'
      - '--cpu=1'
      - '--timeout=300'
      - '--max-instances=100'
      - '--min-instances=0'
    id: 'deploy-cloud-run'

images:
  - 'asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api:$BUILD_ID'
  - 'asia-southeast1-docker.pkg.dev/$PROJECT_ID/ydm-c360-repo/management-api:latest'

options:
  machineType: 'E2_HIGHCPU_8'
  logging: CLOUD_LOGGING_ONLY

substitutions:
  _SERVICE_NAME: 'dev-ydm-c360-manage'
  _REGION: 'asia-southeast1'
  # CORS Configuration - Allow frontend applications to access the API
  # Frontend Admin: https://dev-ydm-c360-mange-907324191702.asia-southeast1.run.app
  # Frontend Client: (add when deployed)
  _CORS_ORIGIN: 'https://dev-ydm-c360-mange-907324191702.asia-southeast1.run.app'

timeout: '1200s'

