name: Release

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

permissions:
  contents: write
  packages: write

jobs:
  build-release:
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Need full history for changelog
      
      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.21'
          cache: true
      
      - name: Run GoReleaser
        uses: goreleaser/goreleaser-action@v5
        with:
          distribution: goreleaser
          version: latest
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: release-artifacts
          path: dist/
          retention-days: 5

  # Optional: Publish to GitHub Packages (requires additional setup)
  publish-packages:
    runs-on: ubuntu-latest
    needs: build-release
    if: startsWith(github.ref, 'refs/tags/')
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
      
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: release-artifacts
          path: dist/
      
      - name: Publish to GitHub Packages
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo "Publishing Debian packages to GitHub Packages..."
          for deb in dist/*.deb; do
            if [ -f "$deb" ]; then
              curl -H "Authorization: token $GITHUB_TOKEN" \
                   -H "Content-Type: application/octet-stream" \
                   --data-binary @"$deb" \
                   "https://uploads.github.com/repos/${{ github.repository }}/releases/upload?name=$(basename "$deb")"
            fi
          done
