name: release 

on:
  push:
    tags:
      - 'v*.*.*'

jobs: 
  build-on-workflow:
    runs-on: ubuntu-latest
    if: |
      github.event_name == 'workflow_run' &&
      github.event.workflow_run.conclusion  == 'success'
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Ensure all history is fetched
          ref: main
        
      - name: Get Latest Tag
        id: get-latest-tag
        if: 
        run: |
          git fetch --tags
          latest_tag=$(git describe --tags `git rev-list --tags --max-count=1`)
          echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT

      - name: Release from Workflow Run
        if: |
          github.event_name == 'workflow_run' &&
          github.event.workflow_run.conclusion  == 'success'
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true 
          append_body: true
          tag_name: ${{ steps.get-latest-tag.outputs.latest_tag }}

  build-on-tag:
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')

    steps: 
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Ensure all history is fetched
          ref: main
      - name: Release from Tag Push
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true 
          append_body: true

  write_changelog:
    runs-on: ubuntu-latest
    needs: [build-on-workflow, build-on-tag]
    if: |
      always() && 
      (needs.build-on-workflow.result == 'success' || needs.build-on-tag.result == 'success' )
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with: 
          fetch-depth: 0  # Ensure all history is fetched
          ref: main
  
      - name: Write CHANGELOG.md      
        uses: rhysd/changelog-from-release/action@v3
        with:
          file: CHANGELOG.md
          github_token: ${{ secrets.GITHUB_TOKEN }}