stages:
  - setup
  - test
  - merge
  - upload
variables:
 # Define all required secrets in GitLab CI/CD variables:
 # SPARTIFY_KEY, PROJECT_ID
  ORDINO_KEY: "$ORDINO_KEY"
  PROJECT_ID: "$PROJECT_ID"

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .npm
    - .cache
setup:
  stage: setup
  image: node:20-alpine
  script:
    - npm run initialize --legacy-peer-deps --omit=optional
  artifacts:
    paths:
      - node_modules
      - .npmrc
      - .npm
    expire_in: 1 hour

run-tests:
  stage: test
  image: cypress/browsers:node-20.17.0-chrome-128.0.6613.119-1-ff-130.0-edge-128.0.2739.63-1
  parallel:
    matrix:
      - SHARD_INDEX: 1
        SHARD_TOTAL: 2
      - SHARD_INDEX: 2
        SHARD_TOTAL: 2
  needs:
    - job: setup
      artifacts: true
  before_script:
    - export CYPRESS_RETRIES=2
    - npx cypress install
  script:
    # Option 1: Using custom shard environment variable
    - npm run oi:run:test -- --env shard=$SHARD_INDEX/$SHARD_TOTAL || true
    # Option 2: Alternative - Using Cypress built-in parallel (requires Cypress Dashboard)
    # - npx cypress run --parallel --record --key $CYPRESS_RECORD_KEY --ci-build-id $CI_PIPELINE_ID || true
    - mkdir -p ordino-report/report-${SHARD_INDEX}
    - "[ -d \"ordino-report/report\" ] && mv ordino-report/report/* ordino-report/report-${SHARD_INDEX}/ || true"
  artifacts:
    paths:
      - ordino-report/report-${SHARD_INDEX}
    when: always
    name: "cypress-report-${SHARD_INDEX}"

merge-reports:
  stage: merge
  image: node:20-alpine
  needs:
    - job: run-tests
      artifacts: true
  script:
    - mkdir -p ordino-report/merged
    - npx -y mochawesome-merge@latest "ordino-report/report-*/*.json" > ordino-report/merged/report.json
  artifacts:
    paths:
      - ordino-report/merged/

upload-report:
  stage: upload
  image: curlimages/curl:latest
  needs:
    - job: merge-reports
      artifacts: true
  script:
    - set -a; [ -f .env ] && source .env; set +a # by deafault, load .env file if it exists 
    - |
      API_URL="{{OrdinoURL}}/api/v1/test-report-external"
      curl --fail-with-body -X POST \
        -H "Spartify-Key: ${ORDINO_KEY}" \
        -F "file=@ordino-report/merged/report.json" \
        -F "ProjectId=${PROJECT_ID}" \
        -F "ExecutionId=${CI_PIPELINE_ID}" \
        "${API_URL}"