# Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
# SPDX-License-Identifier: GPL-3.0-or-later

name: "Publish to Composer"

on:
  push:
    tags:
      - 'v*'
      - '[0-9]*.[0-9]*.[0-9]*'
  release:
    types: [published]
  workflow_dispatch:

env:
  GITEA_URL: ${{ vars.GITEA_URL || 'https://git.mokoconsulting.tech' }}

jobs:
  publish:
    name: Publish Package
    runs-on: ubuntu-latest
    if: >-
      !contains(github.event.head_commit.message, '[skip ci]') &&
      !contains(github.event.head_commit.message, '[skip publish]')
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup PHP
        run: |
          if ! command -v php &> /dev/null; then
            sudo apt-get update -qq
            sudo apt-get install -y -qq php-cli php-mbstring php-xml php-zip php-curl composer >/dev/null 2>&1
          fi

      - name: Install dependencies
        run: composer install --no-dev --no-interaction --prefer-dist --quiet

      - name: Determine version
        id: version
        run: |
          VERSION=$(php -r "echo json_decode(file_get_contents('composer.json'))->version;")
          echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
          echo "Package version: ${VERSION}"

      # Gitea Composer Registry — auto-publishes from tags
      # The tag push itself registers the package at:
      # https://git.mokoconsulting.tech/api/packages/MokoConsulting/composer
      - name: Verify Gitea registry
        run: |
          echo "Gitea Composer registry auto-publishes from tags."
          echo "Package available at: ${GITEA_URL}/api/packages/MokoConsulting/composer"
          echo "Install: composer require mokoconsulting/mokocli"

      # Packagist — notify of new version
      - name: Notify Packagist
        if: secrets.PACKAGIST_TOKEN != ''
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          echo "Notifying Packagist of version ${VERSION}..."
          curl -sf -X POST \
            -H "Content-Type: application/json" \
            -d '{"repository":{"url":"https://git.mokoconsulting.tech/MokoConsulting/mokocli"}}' \
            "https://packagist.org/api/update-package?username=mokoconsulting&apiToken=${{ secrets.PACKAGIST_TOKEN }}" \
            && echo "Packagist notified" \
            || echo "::warning::Packagist notification failed (package may not be registered yet)"

      - name: Summary
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          echo "## Composer Package Published" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Registry | Status |" >> $GITHUB_STEP_SUMMARY
          echo "|----------|--------|" >> $GITHUB_STEP_SUMMARY
          echo "| Gitea | \`composer require mokoconsulting/mokocli:${VERSION}\` |" >> $GITHUB_STEP_SUMMARY
          echo "| Packagist | \`composer require mokoconsulting/mokocli\` |" >> $GITHUB_STEP_SUMMARY
