name: Sync DNS Zones

on:
  push:
    branches:
      - main
      - tnaash
    paths:
      - 'dns/zones/**'
      - 'dns/config.yaml'
  pull_request:
    paths:
      - 'dns/zones/**'
      - 'dns/config.yaml'
  workflow_dispatch:

jobs:
  validate:
    name: Validate DNS Changes
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install --user octodns octodns-cloudflare

      - name: Validate DNS configuration
        env:
          CLOUDFLARE_TOKEN: ${{ secrets.CLOUDFLARE_TOKEN || secrets.CLOUDFLARE_DNS_TOKEN || secrets.CLOUDFLARE_API_TOKEN }}
        working-directory: dns
        run: |
          PATH="$HOME/.local/bin:$PATH"
          octodns-sync --config-file=config.yaml
          echo "✅ DNS validation passed"

  sync:
    name: Apply DNS Changes
    runs-on: ubuntu-latest
    needs: validate
    if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/tnaash')
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install --user octodns octodns-cloudflare

      - name: Sync DNS to Cloudflare
        env:
          CLOUDFLARE_TOKEN: ${{ secrets.CLOUDFLARE_TOKEN || secrets.CLOUDFLARE_DNS_TOKEN || secrets.CLOUDFLARE_API_TOKEN }}
        working-directory: dns
        run: |
          PATH="$HOME/.local/bin:$PATH"
          octodns-sync --config-file=config.yaml --doit
          echo "✅ DNS sync complete"
