name: CI

on:
    push:
        branches: [master]
        tags: ["v*"]
    pull_request:
        branches: [master]

jobs:
    build:
        runs-on: ubuntu-latest

        steps:
            - name: Setup Node.js
              uses: actions/setup-node@v4
              with:
                  node-version: "20"
                  registry-url: "https://registry.npmjs.org"

            - uses: actions/checkout@v4

            - name: Install npm dependencies
              run: npm ci

            - name: Run build
              run: npm run build

            - name: Run tests
              run: npm test

    integration:
        needs: build
        runs-on: ubuntu-latest

        steps:
            - uses: actions/checkout@v4

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

            - name: Install dependencies and build
              run: |
                  npm ci
                  npm run build

            - name: Pack and install package globally
              run: |
                  npm pack
                  npm install -g *.tgz

            - name: Test CLI command execution
              run: |
                  ovh-tools --help
                  ovh-tools --version

    publish:
        needs: [build, integration]
        runs-on: ubuntu-latest
        if: startsWith(github.ref, 'refs/tags/v')
        environment: master

        steps:
            - uses: actions/checkout@v4

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

            - name: Install dependencies
              run: npm ci

            - name: Build
              run: npm run build

            - name: Publish to npm
              run: npm publish
              env:
                  NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
