name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  id-token: write

concurrency:
  group: release-${{ github.ref }}
  cancel-in-progress: false

jobs:
  quality:
    name: Lint, Format & Typecheck
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: "1.3.0"

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Lint
        run: bun run lint

      - name: Format check
        run: bun run fmt:check

      - name: Type check
        run: bun run typecheck

  tests:
    name: Test & Integration
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: "1.3.0"

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Run tests
        run: bun run test

      - name: Run integration tests
        run: bun run test:integration

  publish:
    name: Publish to npm
    runs-on: ubuntu-latest
    needs: [quality, tests]
    steps:
      - uses: actions/checkout@v6

      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: "1.3.0"

      - uses: actions/setup-node@v6
        with:
          node-version: "24"
          registry-url: "https://registry.npmjs.org"

      - name: Install dependencies
        run: bun install --frozen-lockfile

      - name: Build
        run: bun run build

      - name: Verify build output
        run: |
          test -f dist/index.js || (echo "ERROR: dist/index.js not found" && exit 1)
          test -f dist/index.d.ts || (echo "ERROR: dist/index.d.ts not found" && exit 1)

      - name: Verify tag matches package version
        run: |
          TAG_VERSION="${GITHUB_REF#refs/tags/v}"
          PKG_VERSION="$(jq -r '.version' package.json)"
          if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then
            echo "ERROR: Tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)"
            exit 1
          fi

      - name: Publish to npm
        run: npm publish --access public --provenance

  github-release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    needs: [publish]
    steps:
      - uses: actions/checkout@v6

      - name: Create release
        run: gh release create "$GITHUB_REF_NAME" --generate-notes
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
