name: manual publish to npmjs.com and GitHub Pages

on: [workflow_dispatch]

permissions:
  id-token: write
  contents: read

jobs:
  npmjs_deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - uses: actions/setup-node@v4
      with:
        node-version: '20'
        registry-url: 'https://registry.npmjs.org'

    - name: Update npm
      run: npm install -g npm@latest

    - name: Install dependencies
      run: npm ci
    
    - name: Build
      run: npm run build
    
    - name: Run tests
      run: npm test

    - name: Chaek version in repository
      run: |
        NPM_NAME=$(node -p "require('./package.json').name")
        NPM_VERSION=$(node -p "require('./package.json').version")
        echo "Check release version $NPM_NAME@$NPM_VERSION"
        if npm view "$NPM_NAME@$NPM_VERSION" > /dev/null 2>&1; then
          echo "Package $NPM_NAME@$NPM_VERSION already exists, skipping publish."
          echo "publish=false" >> $GITHUB_ENV
        else
          echo "Package $NPM_NAME@$NPM_VERSION not found - will publish."
          echo "publish=true" >> $GITHUB_ENV
        fi

    - name: Publish to npm (trusted publishing)
      if: env.publish == 'true'
      run: npm publish
 
  gh_pages_deploy:
    runs-on: ubuntu-latest
    #runs-on: self-hosted
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v1
      - uses: actions/setup-node@v1
        with:
          node-version: 16
      - run: npm install
      - run: npm run build-script
      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./dist
          keep_files: true
