name: Release

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write

jobs:
  lint:
    uses: ./.github/workflows/lint.yml

  create-release:
    needs: lint
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build application
        run: npm run build
        env:
          VITE_API_URL: /api
          VITE_TELEGRAM_BOT_USERNAME:
          VITE_APP_NAME: Bedolaga Cabinet
          VITE_APP_LOGO: V

      - name: Create dist archive
        run: |
          cd dist
          tar -czf ../bedolaga-cabinet-${{ github.ref_name }}.tar.gz .
          cd ..
          zip -r bedolaga-cabinet-${{ github.ref_name }}.zip dist/

      - name: Generate changelog
        id: changelog
        run: |
          # Get previous tag
          PREV_TAG=$(git describe --tags --abbrev=0 ${{ github.ref_name }}^ 2>/dev/null || echo "")

          if [ -z "$PREV_TAG" ]; then
            echo "changelog=First release" >> $GITHUB_OUTPUT
          else
            CHANGELOG=$(git log ${PREV_TAG}..${{ github.ref_name }} --pretty=format:"- %s (%h)" --no-merges)
            echo "changelog<<EOF" >> $GITHUB_OUTPUT
            echo "$CHANGELOG" >> $GITHUB_OUTPUT
            echo "EOF" >> $GITHUB_OUTPUT
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          body: |
            ## Changes

            ${{ steps.changelog.outputs.changelog }}

            ## Docker Image

            ```bash
            docker pull ghcr.io/${{ github.repository }}:${{ github.ref_name }}
            ```

            ## Installation

            See [README.md](https://github.com/${{ github.repository }}/blob/${{ github.ref_name }}/README.md) for installation instructions.
          files: |
            bedolaga-cabinet-${{ github.ref_name }}.tar.gz
            bedolaga-cabinet-${{ github.ref_name }}.zip
          draft: false
          prerelease: ${{ contains(github.ref_name, 'beta') || contains(github.ref_name, 'alpha') || contains(github.ref_name, 'rc') }}
