name: Release

on:
  push:
    tags:
      - 'v*'

env:
  GO_VERSION: "1.24"

permissions:
  contents: write

jobs:
  # Run tests before releasing
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: ${{ env.GO_VERSION }}

    - name: Download dependencies
      run: go mod download

    - name: Run tests
      run: go test -race ./...

    - name: Run go vet
      run: go vet ./...

  # Build binaries for multiple platforms
  build:
    name: Build
    needs: test
    runs-on: ubuntu-latest
    strategy:
      matrix:
        include:
          - goos: linux
            goarch: amd64
            suffix: ""
          - goos: linux
            goarch: arm64
            suffix: ""
          - goos: darwin
            goarch: amd64
            suffix: ""
          - goos: darwin
            goarch: arm64
            suffix: ""
          - goos: windows
            goarch: amd64
            suffix: ".exe"

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

    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: ${{ env.GO_VERSION }}

    - name: Download dependencies
      run: go mod download

    - name: Build binary
      env:
        GOOS: ${{ matrix.goos }}
        GOARCH: ${{ matrix.goarch }}
      run: |
        VERSION=${GITHUB_REF#refs/tags/}
        COMMIT=$(git rev-parse --short HEAD)
        DATE=$(date -u +%Y-%m-%dT%H:%M:%SZ)
        LDFLAGS="-s -w -X main.Version=$VERSION -X main.Commit=$COMMIT -X main.BuildDate=$DATE"

        mkdir -p dist
        go build -ldflags "$LDFLAGS" -o "dist/jdenticon-${{ matrix.goos }}-${{ matrix.goarch }}${{ matrix.suffix }}" ./cmd/jdenticon/

    - name: Upload artifact
      uses: actions/upload-artifact@v4
      with:
        name: jdenticon-${{ matrix.goos }}-${{ matrix.goarch }}
        path: dist/

  # Create GitHub release with all binaries
  release:
    name: Release
    needs: build
    runs-on: ubuntu-latest

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

    - name: Download all artifacts
      uses: actions/download-artifact@v4
      with:
        path: artifacts

    - name: Prepare release assets
      run: |
        mkdir -p release
        find artifacts -type f -name "jdenticon-*" -exec cp {} release/ \;
        ls -la release/

        # Create checksums
        cd release
        sha256sum * > checksums.txt
        cat checksums.txt

    - name: Create Release
      uses: softprops/action-gh-release@v2
      with:
        files: |
          release/*
        generate_release_notes: true
        draft: false
        prerelease: ${{ contains(github.ref, '-alpha') || contains(github.ref, '-beta') || contains(github.ref, '-rc') }}
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
