name: S3 Sync Production

on:
  push:
    branches:
      - main

jobs:
  sync-and-deploy-production:
    name: Deploy to Production
    runs-on: ubuntu-latest
    environment: production

    permissions:
      id-token: write
      contents: read

    env:
      BUCKET: ${{ vars.BUCKET }}
      PRODUCTION_DIR: "cms_files/production"

    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 Production
        run: |
          aws s3 sync . "s3://$BUCKET/$PRODUCTION_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 "/$PRODUCTION_DIR/*"

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