name: Create Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Extract version info
        id: version
        run: |
          TAG=${GITHUB_REF#refs/tags/}
          VERSION=${TAG#v}
          echo "tag=${TAG}" >> $GITHUB_OUTPUT
          echo "version=${VERSION}" >> $GITHUB_OUTPUT

      - name: Generate release notes
        id: notes
        run: |
          # Get previous tag
          PREV_TAG=$(git tag --sort=-v:refname | head -2 | tail -1)
          if [ "$PREV_TAG" = "${{ steps.version.outputs.tag }}" ] || [ -z "$PREV_TAG" ]; then
            # First release - list all commits
            LOG=$(git log --pretty=format:"- %s" HEAD)
          else
            LOG=$(git log --pretty=format:"- %s" ${PREV_TAG}..HEAD)
          fi
          # Write to file to preserve newlines
          cat <<EOF > release_notes.md
          ## sofarr ${{ steps.version.outputs.tag }}

          ### Docker
          \`\`\`bash
          docker pull docker.i3omb.com/sofarr:${{ steps.version.outputs.version }}
          \`\`\`

          ### Changes
          ${LOG}

          ### Downloads
          - **Source (tar.gz):** [sofarr-${{ steps.version.outputs.tag }}.tar.gz](https://git.i3omb.com/Gandalf/sofarr/archive/${{ steps.version.outputs.tag }}.tar.gz)
          - **Source (zip):** [sofarr-${{ steps.version.outputs.tag }}.zip](https://git.i3omb.com/Gandalf/sofarr/archive/${{ steps.version.outputs.tag }}.zip)
          - **Docker image:** \`docker.i3omb.com/sofarr:${{ steps.version.outputs.version }}\`
          EOF

      - name: Create Gitea Release
        uses: akkuman/gitea-release-action@v1
        with:
          tag_name: ${{ steps.version.outputs.tag }}
          name: "sofarr ${{ steps.version.outputs.tag }}"
          body_path: release_notes.md
        env:
          GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }}
