name: Deploy CultRoll Scraper

on:
  push:
    branches: [main]
    paths:
      - "functions/cultroll-scraper/**"
      - "src/sites/cultroll/lib/**"
      - "package.json"
      - "package-lock.json"
  workflow_dispatch:

jobs:
  deploy:
    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
