name: Notifications on release

on:
  workflow_run:
    workflows: ["Publish Pinepods Multi-Architecture Image to DockerHub"]
    types:
      - completed
  workflow_dispatch:
    inputs:
      message_text:
        description: "Manual override text (optional)"
        required: false

jobs:
  discord_announcement:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Fetch the latest release
        id: fetch_release
        run: |
          latest_release=$(curl -s https://api.github.com/repos/${{ github.repository }}/releases/latest | jq -r '.tag_name')
          release_url=$(curl -s https://api.github.com/repos/${{ github.repository }}/releases/latest | jq -r '.html_url')
          echo "Latest release version: $latest_release"
          echo "Release URL: $release_url"
          echo "::set-output name=version::$latest_release"
          echo "::set-output name=release_url::$release_url"
          
          # Check if this is an RC release
          if [[ "$latest_release" == *"-rc"* ]]; then
            echo "RC release detected, skipping Discord notification"
            echo "::set-output name=is_rc::true"
          else
            echo "::set-output name=is_rc::false"
          fi

      - name: Set release message
        id: set_message
        run: |
          if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
            echo "::set-output name=message::${{ github.event.inputs.message_text }}"
          else
            version="${{ steps.fetch_release.outputs.version }}"
            release_url="${{ steps.fetch_release.outputs.release_url }}"
            message="Pinepods Version $version Released! Check out the release [here]($release_url)"
            echo "::set-output name=message::$message"
          fi

      - name: Skip Discord notification for RC release
        if: steps.fetch_release.outputs.is_rc == 'true'
        run: |
          echo "Skipping Discord notification for RC release: ${{ steps.fetch_release.outputs.version }}"

      - name: Discord notification to announce deployment
        if: steps.fetch_release.outputs.is_rc == 'false'
        env:
          DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
        uses: Ilshidur/action-discord@master
        with:
          args: ${{ steps.set_message.outputs.message }}
