name: Deploy CultRoll Public App

on:
  push:
    branches: [main]
    paths:
      - "src/sites/cultroll/**"
      - "astro.config.cultroll.mjs"
      - "wrangler.cultroll.toml"
      - "package.json"
      - "package-lock.json"
      - "tsconfig.json"
      - "biome.json"
  workflow_dispatch:
    inputs:
      target:
        description: "Deployment target"
        required: true
        default: public
        type: choice
        options:
          - public
          - admin
          - scraper

jobs:
  deploy:
    if: github.event_name != 'workflow_dispatch' || inputs.target == 'public'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    steps:
      - uses: actions/checkout@v4
        with:
          lfs: true

      - uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm

      - run: npm ci
      - run: npm run build:cultroll

      - name: Create Pages project
        continue-on-error: true
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: |
          curl -s -X POST \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"name":"cultroll-web","production_branch":"main"}'

      - name: Prepare wrangler config
        run: cp wrangler.cultroll.toml wrangler.toml

      - name: Set Pages bindings and env vars
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          SCRAPER_ADMIN_TOKEN: ${{ secrets.SCRAPER_ADMIN_TOKEN }}
        run: |
          DB_ID="55ce7f8b-4b90-45f5-a095-69c6266926f1"
          R2_BINDING='{"IMAGES":{"name":"cultroll-images"}}'
          ACCOUNT_SUBDOMAIN=$(curl -s "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq -r '.result.subdomain // empty')
          if [ -n "$ACCOUNT_SUBDOMAIN" ]; then
            SCRAPER_URL="https://cultroll-scraper.${ACCOUNT_SUBDOMAIN}.workers.dev"
          else
            SCRAPER_URL="https://cultroll-scraper.workers.dev"
          fi
          echo "SCRAPER_URL=${SCRAPER_URL}" >> "$GITHUB_ENV"
          if [ -z "${SCRAPER_ADMIN_TOKEN:-}" ]; then
            echo "::error::SCRAPER_ADMIN_TOKEN secret is required"
            exit 1
          fi
          ENV_VARS=$(jq -nc \
            --arg scraperUrl "${SCRAPER_URL}" \
            --arg scraperToken "${SCRAPER_ADMIN_TOKEN}" \
            --arg googleClientId "${{ secrets.CULTROLL_GOOGLE_CLIENT_ID }}" \
            --arg smtp2goApiKey "${{ secrets.SMTP2GO_API_KEY }}" \
            --arg authFromEmail "${{ secrets.CULTROLL_AUTH_FROM_EMAIL }}" \
            --arg authFromName "${{ secrets.CULTROLL_AUTH_FROM_NAME }}" \
            '
            {
              SCRAPER_WORKER_URL: { value: $scraperUrl },
              SCRAPER_ADMIN_TOKEN: { value: $scraperToken, type: "secret_text" }
            }
            + (if $googleClientId != "" then { GOOGLE_CLIENT_ID: { value: $googleClientId } } else {} end)
            + (if $smtp2goApiKey != "" then { SMTP2GO_API_KEY: { value: $smtp2goApiKey, type: "secret_text" } } else {} end)
            + (if $authFromEmail != "" then { AUTH_FROM_EMAIL: { value: $authFromEmail } } else {} end)
            + (if $authFromName != "" then { AUTH_FROM_NAME: { value: $authFromName } } else {} end)
            ')
          curl -s -X PATCH \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects/cultroll-web" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"deployment_configs\":{\"production\":{\"d1_databases\":{\"DB\":{\"id\":\"${DB_ID}\"}},\"r2_buckets\":${R2_BINDING},\"env_vars\":${ENV_VARS}},\"preview\":{\"d1_databases\":{\"DB\":{\"id\":\"${DB_ID}\"}},\"r2_buckets\":${R2_BINDING},\"env_vars\":${ENV_VARS}}}}"

      - name: Deploy to Cloudflare Pages
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: pages deploy dist/cultroll --project-name cultroll-web --branch main

      - name: Add custom domain
        continue-on-error: true
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: |
          curl -s -X POST \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects/cultroll-web/domains" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"name":"cultroll.com"}'

  deploy-admin:
    if: github.event_name == 'workflow_dispatch' && inputs.target == 'admin'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    steps:
      - uses: actions/checkout@v4
        with:
          lfs: true

      - uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm

      - run: npm ci
      - run: npm run build:cultroll-admin

      - name: Create Pages project
        continue-on-error: true
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: |
          curl -s -X POST \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"name":"cultroll-admin-web","production_branch":"main"}'

      - name: Prepare wrangler config
        run: cp wrangler.cultroll-admin.toml wrangler.toml

      - name: Set Pages bindings and env vars
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          SCRAPER_ADMIN_TOKEN: ${{ secrets.SCRAPER_ADMIN_TOKEN }}
        run: |
          DB_ID="55ce7f8b-4b90-45f5-a095-69c6266926f1"
          R2_BINDING='{"IMAGES":{"name":"cultroll-images"}}'
          ACCOUNT_SUBDOMAIN=$(curl -s "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/workers/subdomain" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" | jq -r '.result.subdomain // empty')
          if [ -n "$ACCOUNT_SUBDOMAIN" ]; then
            SCRAPER_URL="https://cultroll-scraper.${ACCOUNT_SUBDOMAIN}.workers.dev"
          else
            SCRAPER_URL="https://cultroll-scraper.workers.dev"
          fi
          if [ -z "${SCRAPER_ADMIN_TOKEN:-}" ]; then
            echo "::error::SCRAPER_ADMIN_TOKEN secret is required"
            exit 1
          fi
          ENV_VARS=$(jq -nc \
            --arg scraperUrl "${SCRAPER_URL}" \
            --arg scraperToken "${SCRAPER_ADMIN_TOKEN}" \
            '{
              SCRAPER_WORKER_URL: { value: $scraperUrl },
              SCRAPER_ADMIN_TOKEN: { value: $scraperToken, type: "secret_text" }
            }')
          curl -s -X PATCH \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects/cultroll-admin-web" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"deployment_configs\":{\"production\":{\"d1_databases\":{\"DB\":{\"id\":\"${DB_ID}\"}},\"r2_buckets\":${R2_BINDING},\"env_vars\":${ENV_VARS}},\"preview\":{\"d1_databases\":{\"DB\":{\"id\":\"${DB_ID}\"}},\"r2_buckets\":${R2_BINDING},\"env_vars\":${ENV_VARS}}}}"

      - name: Deploy to Cloudflare Pages
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: pages deploy dist/cultroll-admin --project-name cultroll-admin-web --branch main

      - name: Add custom domain
        continue-on-error: true
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: |
          curl -s -X POST \
            "https://api.cloudflare.com/client/v4/accounts/${CLOUDFLARE_ACCOUNT_ID}/pages/projects/cultroll-admin-web/domains" \
            -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"name":"portal.cultroll.com"}'

  deploy-scraper:
    if: github.event_name == 'workflow_dispatch' && inputs.target == 'scraper'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write
    steps:
      - uses: actions/checkout@v4
        with:
          lfs: true

      - uses: actions/setup-node@v4
        with:
          node-version: "22"
          cache: npm

      - run: npm ci

      - name: Ensure scraper queues exist
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: |
          set -euo pipefail
          ensure_queue() {
            local queue_name="$1"
            if npx wrangler@4.74.0 queues list | grep -Eq "(^|[[:space:]])${queue_name}([[:space:]]|$)"; then
              echo "Queue exists: ${queue_name}"
            else
              echo "Creating queue: ${queue_name}"
              npx wrangler@4.74.0 queues create "${queue_name}"
            fi
          }
          ensure_queue "cultroll-jobs-dlq"
          ensure_queue "cultroll-jobs"

      - name: Deploy Scraper Worker
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          workingDirectory: functions/cultroll-scraper
          wranglerVersion: "4.74.0"

      - name: Set TMDB_API_KEY Worker secret
        continue-on-error: true
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        working-directory: functions/cultroll-scraper
        run: |
          echo "${{ secrets.TMDB_API_KEY }}" | npx wrangler secret put TMDB_API_KEY

      - name: Set SCRAPER_ADMIN_TOKEN Worker secret
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        working-directory: functions/cultroll-scraper
        run: |
          echo "${{ secrets.SCRAPER_ADMIN_TOKEN }}" | npx wrangler secret put SCRAPER_ADMIN_TOKEN
