name: Publish to GitHub Packages

on:
  push:
    branches:
      - main
    paths:
      - "package.json"
      - "package-lock.json"
      - "src/**"
  workflow_dispatch:
    inputs:
      version_bump:
        description: "Version bump type (patch, minor, major)"
        required: false
        default: "patch"
        type: choice
        options:
          - patch
          - minor
          - major

jobs:
  check-version:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: read
    outputs:
      exists: ${{ steps.check-version.outputs.exists }}
      version: ${{ steps.package-info.outputs.version }}
      name: ${{ steps.package-info.outputs.name }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: "22"
          cache: "npm"

      - name: Get package info
        id: package-info
        run: |
          VERSION=$(node -p "require('./package.json').version")
          NAME=$(node -p "require('./package.json').name")

          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "name=$NAME" >> $GITHUB_OUTPUT
          echo "Package: $NAME@$VERSION"

      - name: Check if version exists
        id: check-version
        run: |
          VERSION=${{ steps.package-info.outputs.version }}
          PACKAGE_NAME="${{ steps.package-info.outputs.name }}"
          OWNER="${{ github.repository_owner }}"
          SCOPED_NAME="@${OWNER}/${PACKAGE_NAME}"

          # Set up GitHub Packages registry
          npm config set registry https://npm.pkg.github.com
          npm config set //npm.pkg.github.com/:_authToken ${{ secrets.GITHUB_TOKEN }}

          # Check if the scoped package version already exists
          if npm view "${SCOPED_NAME}@${VERSION}" version >/dev/null 2>&1; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Version ${VERSION} already exists for ${SCOPED_NAME}, skipping publish"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
            echo "Version ${VERSION} is new for ${SCOPED_NAME}, will publish"
          fi

      - name: Skip summary
        if: steps.check-version.outputs.exists == 'true'
        run: |
          echo "## 📦 Publish Summary"
          echo "Package: ${{ steps.package-info.outputs.name }}@${{ steps.package-info.outputs.version }}"
          echo "✅ Version already exists - skipped publishing (no tests/build run)"

  publish:
    needs: check-version
    if: needs.check-version.outputs.exists == 'false'
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version: "22"
          cache: "npm"

      - name: Install dependencies
        run: npm ci

      - name: Install jq
        run: sudo apt-get update && sudo apt-get install -y jq

      - name: Run tests
        run: npm test

      - name: Build extension
        run: npm run build

      - name: Publish to GitHub Packages
        run: |
          PACKAGE_NAME="${{ needs.check-version.outputs.name }}"
          VERSION=${{ needs.check-version.outputs.version }}
          OWNER="${{ github.repository_owner }}"

          echo "Publishing $PACKAGE_NAME@$VERSION to GitHub Packages..."

          # Configure npm to use GitHub Packages registry
          npm config set registry https://npm.pkg.github.com
          npm config set //npm.pkg.github.com/:_authToken ${{ secrets.GITHUB_TOKEN }}

          # For unscoped packages, GitHub Packages requires the package to be published
          # with the owner namespace. We'll temporarily modify package.json for publishing.
          cp package.json package.json.backup
          jq --arg owner "$OWNER" --arg name "$PACKAGE_NAME" \
             '.name = ("@" + $owner + "/" + $name)' package.json > package.json.temp
          mv package.json.temp package.json

          # Publish to GitHub Packages with scoped name
          npm publish

          # Restore original package.json
          mv package.json.backup package.json

          echo "Successfully published $OWNER/$PACKAGE_NAME@$VERSION to GitHub Packages"
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create Git tag
        run: |
          VERSION=${{ needs.check-version.outputs.version }}
          PACKAGE_NAME="${{ needs.check-version.outputs.name }}"

          TAG_NAME="v$VERSION"

          # Check if tag already exists
          if git tag -l | grep -q "^$TAG_NAME$"; then
            echo "Tag $TAG_NAME already exists, skipping tag creation"
          else
            echo "Creating tag $TAG_NAME"
            git config --local user.email "action@github.com"
            git config --local user.name "GitHub Action"
            git tag "$TAG_NAME"
            git push origin "$TAG_NAME"
            echo "Tag $TAG_NAME created and pushed"
          fi

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: v${{ needs.check-version.outputs.version }}
          name: v${{ needs.check-version.outputs.version }}
          body: |
            ## ${{ needs.check-version.outputs.name }}@v${{ needs.check-version.outputs.version }}

            **Published to GitHub Packages**

            ### Installation

            ```bash
            npm install @${{ github.repository_owner }}/${{ needs.check-version.outputs.name }} --registry=https://npm.pkg.github.com
            ```

            Or add to your `.npmrc`:

            ```
            @${{ github.repository_owner }}:registry=https://npm.pkg.github.com
            //npm.pkg.github.com/:_authToken=YOUR_GITHUB_TOKEN
            ```

            Then install:

            ```bash
            npm install @${{ github.repository_owner }}/${{ needs.check-version.outputs.name }}
            ```

            ### What's New

            - Automated release from CI/CD pipeline
            - All tests passed ✅
            - Extension built successfully ✅

          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish Summary
        run: |
          echo "## 📦 Publish Summary"
          echo "Package: ${{ needs.check-version.outputs.name }}@${{ needs.check-version.outputs.version }}"
          echo "✅ Successfully published to GitHub Packages"
          echo "🏷️  Created tag: v${{ needs.check-version.outputs.version }}"
          echo "📝 Created release: v${{ needs.check-version.outputs.version }}"
          echo ""
          echo "### 🔗 Links"
          echo "- **GitHub Packages**: https://github.com/${{ github.repository }}/packages"
          echo "- **Install Command**: npm install @${{ github.repository_owner }}/${{ needs.check-version.outputs.name }} --registry=https://npm.pkg.github.com"
          echo "- **Release**: https://github.com/${{ github.repository }}/releases/tag/v${{ needs.check-version.outputs.version }}"
