trigger:
  tags:
    include:
      - "v*"

resources:
  containers:
    - container: node18
      image: node:18-buster

pool:
  docker-new

variables:
- group: ado-gh-sync-vg   # contains GITHUB_APP_ID and GITHUB_APP_INSTALLATION_ID

jobs:
# ---- Gate: run unit tests + enforce 90% coverage BEFORE anything is built/synced ----
- job: Test
  displayName: 'Unit tests & 90% coverage gate'
  container: node18
  steps:
  - checkout: self

  - script: |
      set -euo pipefail

      echo "Installing dependencies (incl. devDependencies for jest/ts-jest)..."
      NODE_ENV=development npm install

      echo "Running unit tests with enforced 90% coverage threshold..."
      # 'npm run test' runs jest with coverageThreshold=90 in jest.config.js.
      # Jest exits non-zero if ANY test fails OR if coverage falls below 90%,
      # which fails this step -> fails this job -> the GitHubSync job is skipped.
      npm run test

      echo "Generating coverage summary (coverage/coverage_output.json)..."
      npm run coverage:output
    displayName: 'Run tests (fails if any test fails or coverage < 90%)'

  - task: PublishCodeCoverageResults@1
    displayName: 'Publish code coverage report'
    condition: succeededOrFailed()
    inputs:
      codeCoverageTool: 'Cobertura'
      summaryFileLocation: '$(System.DefaultWorkingDirectory)/coverage/cobertura-coverage.xml'

# ---- Build / GitHub sync: only runs if the Test gate above passed ----
- job: GitHubSync
  dependsOn: Test
  condition: succeeded()
  container: node18
  steps:
  - checkout: self

  - task: DownloadSecureFile@1
    name: githubAppKey
    inputs:
      secureFile: 'ado-gh-sync.pem'

  - script: |
      set -euo pipefail

      echo "Tag build: $(Build.SourceBranchName)"

      TAG_NAME="$(Build.SourceBranchName)"
      BRANCH_NAME=main

      if [[ "$TAG_NAME" == *"-"* ]]; then
        IS_PRERELEASE=true
      else
        IS_PRERELEASE=false
      fi

      echo "Is prerelease: $IS_PRERELEASE"

      git config --global user.email "jigar.dafda@gmail.com"
      git config --global user.name "Jigar Dafda"

      # ---- Generate GitHub App JWT (RS256) ----
      export GITHUB_APP_PEM_PATH="$(githubAppKey.secureFilePath)"

      node <<'NODE'
      const fs = require('fs');
      const crypto = require('crypto');

      function b64url(input) {
        return Buffer.from(input).toString('base64')
          .replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
      }

      const appId = process.env.GITHUB_APP_ID;
      const pemPath = process.env.GITHUB_APP_PEM_PATH;

      if (!appId || !pemPath) {
        console.error("Missing env: GITHUB_APP_ID / GITHUB_APP_PEM_PATH");
        process.exit(1);
      }

      const privateKey = fs.readFileSync(pemPath, 'utf8');

      const now = Math.floor(Date.now() / 1000);
      const header = { alg: "RS256", typ: "JWT" };
      const payload = {
        iat: now - 30,
        exp: now + 9 * 60, // <= 10 minutes
        iss: appId
      };

      const unsigned = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(payload))}`;
      const sign = crypto.createSign('RSA-SHA256');
      sign.update(unsigned);
      const signature = sign.sign(privateKey);
      const jwt = `${unsigned}.${b64url(signature)}`;

      fs.writeFileSync('github_app_jwt.txt', jwt);
      NODE

      JWT="$(cat github_app_jwt.txt)"

      # ---- Exchange JWT for Installation Access Token ----
      INSTALL_TOKEN="$(
        curl -sS -X POST \
          -H "Authorization: Bearer ${JWT}" \
          -H "Accept: application/vnd.github+json" \
          "https://api.github.com/app/installations/${GITHUB_APP_INSTALLATION_ID}/access_tokens" \
        | node -pe "JSON.parse(require('fs').readFileSync(0,'utf8')).token"
      )"

      if [ -z "$INSTALL_TOKEN" ] || [ "$INSTALL_TOKEN" = "undefined" ]; then
        echo "Failed to get installation token"
        exit 1
      fi

      # Build header for git HTTPS auth with GitHub App token
      BASIC_B64="$(printf '%s:%s' "x-access-token" "$INSTALL_TOKEN" | base64 | tr -d '\n')"
      AUTH_HEADER="Authorization: Basic ${BASIC_B64}"

      # ---- Sync flow ----
      git -c http.extraheader="$AUTH_HEADER" clone https://github.com/gofynd/fdk-store-gql.git
      cd fdk-store-gql
      git checkout "$BRANCH_NAME"

      rm -rf ./*
      cd ..

      cp -R $(ls | grep -v "fdk-store-gql") ./fdk-store-gql
      cp .gitignore.ci ./fdk-store-gql/.gitignore

      cd fdk-store-gql
      NODE_ENV=development npm install
      npm run build

      # Capture release notes from CHANGELOG.md before any push; a missing/empty
      # section exits non-zero and (via set -e) fails the job here.
      RELEASE_BODY="$(node scripts/extract-changelog.js CHANGELOG.md "$TAG_NAME")"

      git add -A
      git commit -m "[Auto Generated]" || echo "No changes to commit"

      git -c http.extraheader="$AUTH_HEADER" push origin "$BRANCH_NAME"

      git tag "$TAG_NAME" || echo "Tag already exists locally"
      git -c http.extraheader="$AUTH_HEADER" push origin "$TAG_NAME"

      # Create GitHub release. Build the JSON with JSON.stringify so the
      # markdown body is safely escaped.
      POST_DATA="$(
        TAG_NAME="$TAG_NAME" \
        BRANCH_NAME="$BRANCH_NAME" \
        IS_PRERELEASE="$IS_PRERELEASE" \
        RELEASE_BODY="$RELEASE_BODY" \
        node -e '
          process.stdout.write(JSON.stringify({
            tag_name: process.env.TAG_NAME,
            target_commitish: process.env.BRANCH_NAME,
            name: "Release_" + process.env.TAG_NAME,
            body: process.env.RELEASE_BODY,
            draft: false,
            prerelease: process.env.IS_PRERELEASE === "true",
          }));
        '
      )"

      curl -sS -X POST \
        -H "Authorization: token ${INSTALL_TOKEN}" \
        -H "Accept: application/vnd.github+json" \
        -H "Content-Type: application/json" \
        -d "$POST_DATA" \
        "https://api.github.com/repos/gofynd/fdk-store-gql/releases"
    displayName: 'Sync with GitHub (GitHub App auth)'
    env:
      GITHUB_APP_ID: $(GITHUB_APP_ID)
      GITHUB_APP_INSTALLATION_ID: $(GITHUB_APP_INSTALLATION_ID)