name: Deploy llink-web

on:
  workflow_dispatch:
    inputs:
      environment:
        description: "Target environment"
        required: true
        type: choice
        options: [dev, prod]

concurrency:
  group: deploy-llink-web-${{ inputs.environment }}
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    environment: ${{ inputs.environment }}
    defaults:
      run:
        working-directory: js/desktop
    steps:
      - uses: actions/checkout@v4

      - name: Resolve environment settings
        id: env
        run: |
          case "${{ inputs.environment }}" in
            dev)
              echo "project=flowy-dev-440017"  >> "$GITHUB_OUTPUT"
              echo "cluster=cluster"           >> "$GITHUB_OUTPUT"
              ;;
            prod)
              echo "project=flowy-prod-440017" >> "$GITHUB_OUTPUT"
              echo "cluster=prod-cluster"      >> "$GITHUB_OUTPUT"
              ;;
            *)
              echo "Unknown environment: ${{ inputs.environment }}" >&2; exit 1
              ;;
          esac
          echo "region=us-west2" >> "$GITHUB_OUTPUT"

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ inputs.environment == 'prod' && secrets.PROD_GKE_SERVICE_ACCOUNT_KEY || secrets.DEV_GKE_SERVICE_ACCOUNT_KEY }}

      - uses: google-github-actions/setup-gcloud@v2

      - name: Install gke-gcloud-auth-plugin
        run: gcloud components install gke-gcloud-auth-plugin --quiet

      - name: Configure Docker for Artifact Registry
        run: gcloud auth configure-docker us-west2-docker.pkg.dev --quiet

      - name: Get GKE credentials
        run: |
          gcloud container clusters get-credentials "${{ steps.env.outputs.cluster }}" \
            --region "${{ steps.env.outputs.region }}" \
            --project "${{ steps.env.outputs.project }}"

      - name: Install skaffold
        run: |
          curl -fsSLo skaffold https://storage.googleapis.com/skaffold/releases/latest/skaffold-linux-amd64
          sudo install skaffold /usr/local/bin/
          skaffold version

      - name: Deploy
        env:
          SKAFFOLD_DEFAULT_REPO: us-west2-docker.pkg.dev/${{ steps.env.outputs.project }}/deployments
        run: skaffold run -p ${{ inputs.environment }}
