name: 🚀 Deploy cloud-mail to Cloudflare Workers

on:
  push:
    branches: [ main ]
    paths:
      - "mail-worker/**"
      - "mail-vue/**"
  workflow_dispatch:

jobs:
  Deploy-cloud-mail:
    name: 🏗️ Build and Deploy
    runs-on: ubuntu-latest

    env:
      CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
      CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
      D1_DATABASE_ID: ${{ secrets.D1_DATABASE_ID }}
      KV_NAMESPACE_ID: ${{ secrets.KV_NAMESPACE_ID }}
      R2_BUCKET_NAME: ${{ secrets.R2_BUCKET_NAME }}
      DOMAIN: ${{ secrets.DOMAIN }}
      ADMIN: ${{ secrets.ADMIN }}
      JWT_SECRET: ${{ secrets.JWT_SECRET }}
      INIT_URL: ${{ secrets.INIT_URL }}
    
    outputs:
      deployment_skipped: ${{ steps.deploy.outputs.deployment_skipped }}

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

      - name: 📦 Setup pnpm
        uses: pnpm/action-setup@v4.1.0
        with:
          version: latest

      - name: 📦 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20"
          cache: "pnpm"
          cache-dependency-path: "./mail-worker/pnpm-lock.yaml"

      - name: 📥 Install dependencies
        run: pnpm install --frozen-lockfile
        working-directory: ./mail-worker

      - name: 📡 Disable wrangler telemetry
        working-directory: ./mail-worker
        run: npx wrangler telemetry disable

      - name: 🛠️ Prepare Config, Set Secrets and Deploy
        id: deploy
        working-directory: ./mail-worker
        run: |
          if [ -z "$D1_DATABASE_ID" ] || [ -z "$KV_NAMESPACE_ID" ] || [ -z "$R2_BUCKET_NAME" ]; then
            echo "⚠️ Required secrets (D1_DATABASE_ID, KV_NAMESPACE_ID, or R2_BUCKET_NAME) are not set."
            echo "🟡 Skipping deployment."
            echo "deployment_skipped=true" >> $GITHUB_OUTPUT
            exit 0
          fi
          
          echo "deployment_skipped=false" >> $GITHUB_OUTPUT
          CONFIG_FILE="wrangler-action.toml"
          echo "⚙️ Dynamically updating '$CONFIG_FILE' with binding IDs..."

          sed -i "s|\${D1_DATABASE_ID}|${D1_DATABASE_ID}|g" "$CONFIG_FILE"
          sed -i "s|\${KV_NAMESPACE_ID}|${KV_NAMESPACE_ID}|g" "$CONFIG_FILE"
          sed -i "s|\${R2_BUCKET_NAME}|${R2_BUCKET_NAME}|g" "$CONFIG_FILE"

          echo "🔍 Debug: Checking configuration after replacement..."
          echo "R2_BUCKET_NAME value: '$R2_BUCKET_NAME'"
          echo "R2 bucket configuration in $CONFIG_FILE:"
          grep -A 2 -B 2 "bucket_name" "$CONFIG_FILE" || true

          echo "🔒 Setting Worker secrets..."
          WORKER_NAME="cloud-mail"
          for VAR in DOMAIN ADMIN JWT_SECRET; do
            if [ -n "${!VAR}" ]; then
              VAR_LOWER=$(echo "$VAR" | tr '[:upper:]' '[:lower:]')
              echo ">> Processing secret: '$VAR_LOWER'"
              (echo "${!VAR}" | npx wrangler secret put "$VAR_LOWER" --name "$WORKER_NAME" -c "$CONFIG_FILE") || true
            else
              echo "⚠️ Warning: GitHub Secret '$VAR' is not set. Skipping."
            fi
          done

          echo "🚀 Configuration updated. Starting deployment..."
          npx wrangler deploy -c "$CONFIG_FILE" | grep -v "https://.*\.workers\.dev" || true
          echo "✅ Deployment command executed."

      - name: 🗄️ Initialize Database (if INIT_URL is set)
        if: ${{ steps.deploy.outputs.deployment_skipped == 'false' }}
        run: |
          if [ -z "$INIT_URL" ]; then
            echo "✅ Deployment successful. INIT_URL not set, skipping initialization."
            exit 0
          fi
          
          echo "⏳ Waiting 15 秒之前 before checking initialization status..."
          sleep 15
          
          HTTP_CODE=$(curl -s -w "%{http_code}" -o response.txt "$INIT_URL")
          RESPONSE_BODY=$(cat response.txt)
          
          echo "🔎 Checking response... (Status: $HTTP_CODE)"

          if [ "$HTTP_CODE" = "200" ] && [ "$RESPONSE_BODY" = "初始化成功" ]; then
            echo "🎉✅ Fresh initialization successful!"
          elif [ "$HTTP_CODE" = "200" ]; then
            echo "✅ Database is already initialized or in a stable state. Response: $RESPONSE_BODY"
          else
            echo "⚠️ Database initialization check failed with HTTP status: $HTTP_CODE. Please check your worker logs."
          fi

      - name: 📣 Notify Final Status
        if: always()
        run: |
          if [ "${{ job.status }}" == "success" ]; then
            if [ "${{ steps.deploy.outputs.deployment_skipped }}" == "true" ]; then
              echo "🟡 Deployment was skipped due to missing configuration."
            else
              echo "🎉🎉🎉 Hooray! Deployment completed successfully! 🎉🎉🎉"
            fi
          else
            echo "❌❌❌ Oh no! The deployment failed. Please check the logs above for errors. ❌❌❌"
          fi

      - name: Delete workflow runs
        uses: GitRML/delete-workflow-runs@main
        with:
          retain_days: '3'
          keep_minimum_runs: '0'
