name: Publish Package

on:
  push:
    branches: 
      - main

permissions:
  contents: read
  packages: write
  deployments: write

jobs:
  publish-npmjs:
    name: Publish to npmjs.org
    runs-on: ubuntu-latest

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

      - name: Setup Node.js for npmjs.org
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'
          scope: '@galihru'

      - name: Install dependencies
        run: npm install

      - name: Build package
        run: npm run

      - name: Publish to npmjs.org
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
        run: |
          echo "//registry.npmjs.org/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc
          npm publish --access public

      - name: Create deployment status for npmjs
        uses: actions/github-script@v7
        with:
          script: |
            const pkg = require('./package.json');
            const deployment = await github.rest.repos.createDeployment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              ref: context.ref,
              environment: 'npmjs',
              description: `Published @galihru/pqlaicrypto@${pkg.version}`,
              auto_merge: false,
              required_contexts: []
            });
            await github.rest.repos.createDeploymentStatus({
              owner: context.repo.owner,
              repo: context.repo.repo,
              deployment_id: deployment.data.id,
              state: 'success',
              environment_url: `https://www.npmjs.com/package/@galihru/pqlaicrypto`,
              log_url: `https://www.npmjs.com/package/@galihru/pqlaicrypto`,
              description: `Version ${pkg.version} published to npmjs`
            });

  publish-github-packages:
    name: Publish to GitHub Packages
    runs-on: ubuntu-latest
    needs: publish-npmjs

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

      - name: Setup Node.js for GitHub Packages
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@galihru'

      - name: Install dependencies
        run: npm install

      - name: Build package
        run: npm run

      - name: Publish to GitHub Packages
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          echo "//npm.pkg.github.com/:_authToken=$NODE_AUTH_TOKEN" > ~/.npmrc
          echo "@galihru:registry=https://npm.pkg.github.com" >> ~/.npmrc
          npm publish
