name: Deploy TNAASH to Cloudflare Pages

on:
  push:
    branches:
      - main
      - tnaash
    paths:
      - 'src/sites/tnaash/**'
      - 'src/shared/**'
      - 'src/assets/src/tnaash-*'
      - 'src/assets/out/tnaash-*'
      - 'src/assets/lib/**'
      - 'astro.config.tnaash.mjs'
      - 'wrangler.tnaash.toml'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      deployments: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          lfs: true

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build TNAASH site
        env:
          PUBLIC_TURNSTILE_SITE_KEY: ${{ secrets.TNAASH_TURNSTILE_SITE_KEY }}
        run: npm run build:tnaash

      - name: Create Pages project (if not exists)
        continue-on-error: true
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          command: pages project create tnaash-web --production-branch=main

      - 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/tnaash --project-name=tnaash-web --branch=main --commit-dirty=true
          gitHubToken: ${{ secrets.GITHUB_TOKEN }}

      - name: Add custom domain to Pages project
        continue-on-error: true
        run: |
          RESP=$(curl -s -X POST \
            "https://api.cloudflare.com/client/v4/accounts/${{ secrets.CLOUDFLARE_ACCOUNT_ID }}/pages/projects/tnaash-web/domains" \
            -H "Authorization: Bearer ${{ secrets.CLOUDFLARE_API_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d '{"name":"tnaash.mov"}')
          echo "API response: $RESP"
          echo "$RESP" | python3 -c "import json,sys; r=json.load(sys.stdin); result=r.get('result') or {}; errors=r.get('errors',[]); print('Domain:', result.get('name','n/a'), '| Status:', result.get('status','n/a'), '| Errors:', errors)"
