on:
  workflow_call:
    outputs:
      version:
        description: "App Version"
        value: ${{ jobs.release.outputs.version }}

name: "Release Record Web Version"

permissions:
  contents: write
  issues: write
  pull-requests: write
  id-token: write

jobs:
  release:
    runs-on: [self-hosted, linux, x64, ubuntu]
    name: Release
    outputs:
      version: ${{ steps.set-version.outputs.new_release_version }}
    steps:
    - name: Checkout
      uses: actions/checkout@v6
      with:
        fetch-depth: 0
    - uses: actions/setup-node@v6
      with:
        node-version-file: '.nvmrc'
    - name: Enable Corepack
      run: corepack enable
    - name: Prepare pnpm
      run: corepack install

    - name: Verify Jira API access
      if: github.ref == 'refs/heads/staging' || github.ref == 'refs/heads/main'
      env:
        JIRA_USER: ${{ secrets.JIRA_USER }}
        JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }}
      run: |
        if [ -z "$JIRA_USER" ] || [ -z "$JIRA_TOKEN" ]; then
          echo "::warning::JIRA_USER or JIRA_TOKEN is missing. Skipping Jira sync."
          echo "ENABLE_JIRA_RELEASE=false" >> $GITHUB_ENV
          exit 0
        fi

        JIRA_HTTP_CODE=$(curl -sS -o /dev/null -w "%{http_code}" \
          -u "$JIRA_USER:$JIRA_TOKEN" \
          -H "Accept: application/json" \
          "https://accedobroadband.jira.com/rest/api/3/project/RECORD")

        if [ "$JIRA_HTTP_CODE" = "200" ]; then
          echo "ENABLE_JIRA_RELEASE=true" >> $GITHUB_ENV
        else
          echo "::warning::Jira API check failed with HTTP $JIRA_HTTP_CODE. Skipping Jira sync."
          echo "ENABLE_JIRA_RELEASE=false" >> $GITHUB_ENV
        fi

    - name: Semantic Release
      uses: cycjimmy/semantic-release-action@v4
      id: release
      with:
        extra_plugins: |
          @semantic-release/release-notes-generator
          @semantic-release/commit-analyzer
          @semantic-release/exec
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        JIRA_USER: ${{ secrets.JIRA_USER }}
        JIRA_TOKEN: ${{ secrets.JIRA_TOKEN }}

    - name: Set version output
      id: set-version
      run: |
        echo "new_release_version=${{ steps.release.outputs.new_release_version }}" >> $GITHUB_OUTPUT
