name: S3 Sync Staging

on:
  push:
    branches:
      - staging
  pull_request:
    types: [labeled, synchronize]

jobs:
  sync-and-deploy-staging:
    name: Deploy to Staging
    runs-on: ubuntu-latest
    environment: staging
    if: >
      github.event_name == 'push' ||
      (
        github.event_name == 'pull_request' &&
        github.event.pull_request.head.repo.full_name == github.repository &&
        contains(github.event.pull_request.labels.*.name, 'staging')
      )

    permissions:
      id-token: write
      contents: read

    env:
      BUCKET: ${{ vars.BUCKET }}
      STAGING_DIR: "cms_files/staging"

    steps:
      - name: Checkout files
        uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0

      - name: Prepare environment
        uses: ./.github/actions/prepare
        with:
          aws_role: ${{ vars.AWS_ROLE_TO_ASSUME}}

      - name: Sync files to Staging
        run: |
          aws s3 sync . "s3://$BUCKET/$STAGING_DIR" \
            --acl public-read \
            --follow-symlinks \
            --delete \
            --exclude ".git/*" \
            --exclude ".github/*" \
            --exclude ".gitignore" \
            --exclude "README.md" \
            --exclude ".DS_Store" \
            --exclude "src/*" \
            --exclude ".env" \
            --exclude ".env.*" \
            --exclude "esbuild.*" \
            --exclude "package.json" \
            --exclude "package-lock.json"

      - name: Invalidate dentolo Cloudfront
        run: |
          aws cloudfront create-invalidation \
            --distribution-id ${{ secrets.AWS_DENTOLO_DISTRIBUTION }} \
            --paths "/$STAGING_DIR/*"

      - name: Invalidate petolo Cloudfront
        run: |
          aws cloudfront create-invalidation \
            --distribution-id ${{ secrets.AWS_PETOLO_DISTRIBUTION }} \
            --paths "/$STAGING_DIR/*"
