name: Release

on:
  push:
    branches:
      - main
    paths:
      - "Cargo.toml"

permissions:
  contents: write

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.read_toml.outputs.value }}
      should_release: ${{ steps.check_tag.outputs.should_release }}

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Read version from Cargo.toml
        id: read_toml
        uses: SebRollen/toml-action@v1.2.0
        with:
          file: Cargo.toml
          field: package.version

      - name: Check if tag exists
        id: check_tag
        run: |
          if git rev-parse "v${{ steps.read_toml.outputs.value }}" >/dev/null 2>&1; then
            echo "should_release=false" >> $GITHUB_OUTPUT
          else
            echo "should_release=true" >> $GITHUB_OUTPUT
          fi

  build:
    needs: check-version
    if: needs.check-version.outputs.should_release == 'true'
    runs-on: windows-latest

    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Cache dependencies
        uses: Swatinem/rust-cache@v2

      - name: Build
        run: cargo build --release

      - name: Bump version and push tag
        id: tag_version
        uses: mathieudutour/github-tag-action@v6.2
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          custom_tag: ${{ needs.check-version.outputs.version }}

      - name: Build changelog
        id: build_changelog
        uses: mikepenz/release-changelog-builder-action@v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          toTag: ${{ steps.tag_version.outputs.new_tag }}
          configurationJson: |
            {
              "categories": [
                {
                    "title": "",
                    "labels": []
                }
              ],
              "pr_template": "- #{{TITLE}} by @#{{AUTHOR}} in #{{URL}}",
              "template": "#{{CHANGELOG}}\n\n**Full Changelog**: https://github.com/${{ github.repository }}/compare/#{{FROM_TAG}}...#{{TO_TAG}}"
            }

      - name: Create Release
        uses: ncipollo/release-action@v1
        with:
          tag: ${{ steps.tag_version.outputs.new_tag }}
          name: Release ${{ steps.tag_version.outputs.new_tag }}
          token: ${{ secrets.GITHUB_TOKEN }}
          artifacts: target/release/lunar-chess.exe
          body: |
            ## What's Changed:
            ${{ steps.build_changelog.outputs.changelog }}

      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish
