name: Publish FlexiDatepicker

on:
  release:
    types: [created]

jobs:
  build:
    name: Build and Test
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 23
          registry-url: 'https://registry.npmjs.org/'
          cache: 'npm'

      - name: Clean install
        run: |
          rm -rf node_modules package-lock.json
          npm install --ignore-scripts
          npm rebuild rollup --build-from-source

      - name: Build library
        run: |
          if npm run | grep -q "build"; then
            npm run build
          else
            echo "No build script found."
          fi

      - name: Run tests (if defined)
        run: |
          if npm run | grep -q "test"; then
            npm test
          else
            echo "No tests found, skipping..."
          fi

  publish-npm:
    name: Publish to npmjs.com
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: read

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js for publish
        uses: actions/setup-node@v4
        with:
          node-version: 23
          registry-url: 'https://registry.npmjs.org/'
          cache: 'npm'

      - name: Install dependencies
        run: |
          npm ci --ignore-scripts
          npm rebuild rollup --build-from-source

      - name: Verify npm user
        run: npm whoami
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
          
      - name: Publish to npmjs
        run: |
          npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
