name: CI Test Cleanup
on:
  workflow_dispatch:
  schedule:
    # every half hour
    - cron: "*/30 * * * *"

jobs:
  Test-User-Data-Cleanup:
    environment: Testing
    runs-on: ubuntu-latest
    continue-on-error: true
    strategy:
      matrix:
        user: [ CORSO_M365_TEST_USER_ID, CORSO_SECONDARY_M365_TEST_USER_ID, '' ]

    steps:
      - uses: actions/checkout@v4

      # sets the maximum time to now-30m.
      # CI test have a 20 minute timeout.
      - name: Set purge boundary
        run: echo "HALF_HOUR_AGO=$(date -d '30 minutes ago' -u +"%Y-%m-%dT%H:%M:%SZ")" >> $GITHUB_ENV

      - name: Purge CI-Produced Folders for Users
        uses: ./.github/actions/purge-m365-data
        with:
          user: ${{ vars[matrix.user] }}
          folder-prefix: ${{ vars.CORSO_M365_TEST_PREFIXES }}
          older-than: ${{ env.HALF_HOUR_AGO }}
          azure-client-id: ${{ secrets.CLIENT_ID }}
          azure-client-secret: ${{ secrets.CLIENT_SECRET }}
          azure-tenant-id: ${{ secrets.TENANT_ID }}
          m365-admin-user: ${{ secrets.M365_TENANT_ADMIN_USER }}
          m365-admin-password: ${{ secrets.M365_TENANT_ADMIN_PASSWORD }}

      - name: Notify failure in teams
        if: failure()
        uses: ./.github/actions/teams-message
        with:
          msg: "[FAILED] ${{ vars[matrix.user] }} CI Cleanup"
          teams_url: ${{ secrets.TEAMS_CORSO_CI_WEBHOOK_URL }}

  Test-Site-Data-Cleanup:
    environment: Testing
    runs-on: ubuntu-latest
    continue-on-error: true
    strategy:
      matrix:
        site: [ CORSO_M365_TEST_SITE_URL, CORSO_M365_TEST_GROUPS_SITE_URL ] 

    steps:
      - uses: actions/checkout@v4

      # sets the maximum time to now-30m.
      # CI test have a 20 minute timeout.
      - name: Set purge boundary
        run: echo "HALF_HOUR_AGO=$(date -d '30 minutes ago' -u +"%Y-%m-%dT%H:%M:%SZ")" >> $GITHUB_ENV

      - name: Purge CI-Produced Folders for Sites
        uses: ./.github/actions/purge-m365-data
        with:
          site: ${{ vars[matrix.site] }}
          folder-prefix: ${{ vars.CORSO_M365_TEST_PREFIXES }}
          libraries: ${{ vars.CORSO_M365_TEST_SITE_LIBRARIES }}
          library-prefix: ${{ vars.CORSO_M365_TEST_PREFIXES }}
          older-than: ${{ env.HALF_HOUR_AGO }}
          azure-client-id: ${{ secrets.CLIENT_ID }}
          azure-client-secret: ${{ secrets.CLIENT_SECRET }}
          azure-tenant-id: ${{ secrets.TENANT_ID }}
          m365-admin-user: ${{ secrets.M365_TENANT_ADMIN_USER }}
          m365-admin-password: ${{ secrets.M365_TENANT_ADMIN_PASSWORD }}

      - name: Notify failure in teams
        if: failure()
        uses: ./.github/actions/teams-message
        with:
          msg: "[FAILED] ${{ vars[matrix.site] }} CI Cleanup"
          teams_url: ${{ secrets.TEAMS_CORSO_CI_WEBHOOK_URL }}
