name: Deploy CULTGUARD to Cloudflare Pages

on:
  push:
    branches:
      - main
    paths:
      - 'src/sites/cultguard/**'
      - 'src/shared/**'
      - 'src/assets/src/cultguard-*'
      - 'src/assets/out/cultguard-*'
      - 'src/assets/src/icons/**'
      - 'astro.config.cultguard.mjs'
      - 'wrangler.cultguard.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 CULTGUARD site
        run: npm run build:cultguard

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

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