stages:
  - build
  - deploy

cache:
  # cache:key 这里使用字符串，兼容性更好（部分 linter 不支持 key: { files: [...] }）
  # 预分支 pre 需要快速构建并实时同步，因此让 .npm 下载缓存跨分支复用
  key: "npm-cache-global"
  paths:
    - .npm/
  policy: pull-push

build_pre:
  stage: build
  image: node:20-bullseye
  tags:
    - risk-monitor-frontend
  only:
    - pre
  script:
    - node -v
    - npm -v
    - echo "cache dir sizes:"
    - du -sh "$CI_PROJECT_DIR/.npm" "$CI_PROJECT_DIR/.npm/_cacache" 2>/dev/null || true
    - echo "=== npm ci start ==="
    - date -Iseconds
    - npm ci --cache "$CI_PROJECT_DIR/.npm" --no-audit --no-fund --include=optional --loglevel=verbose --timing --foreground-scripts
    - echo "=== npm ci end ==="
    - date -Iseconds
    - npm run build
  artifacts:
    paths:
      - dist/
    expire_in: 1 hour

deploy_pre:
  stage: deploy
  image: alpine:3.20
  tags:
    - risk-monitor-frontend
  only:
    - pre
  dependencies:
    - build_pre
  script:
    - apk add --no-cache rsync curl jq
    # 只允许“最新一次 pre pipeline”部署到 nginx（加二次确认，避免短时间多次推送导致重复 rsync）
    - >
      LATEST_PIPELINE_ID="$(
      curl --silent --show-error --fail
      --header "JOB-TOKEN: $CI_JOB_TOKEN"
      "$CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/pipelines?ref=pre&order_by=id&sort=desc&per_page=1"
      | jq -r '.[0].id'
      )"
    - >
      if [ -z "$LATEST_PIPELINE_ID" ] || [ "$LATEST_PIPELINE_ID" != "$CI_PIPELINE_ID" ]; then
        echo "skip deploy: not latest pipeline (latest=$LATEST_PIPELINE_ID current=$CI_PIPELINE_ID)";
        exit 0;
      fi
    - sleep 20
    - >
      LATEST_PIPELINE_ID="$(
      curl --silent --show-error --fail
      --header "JOB-TOKEN: $CI_JOB_TOKEN"
      "$CI_SERVER_URL/api/v4/projects/$CI_PROJECT_ID/pipelines?ref=pre&order_by=id&sort=desc&per_page=1"
      | jq -r '.[0].id'
      )"
    - >
      if [ -z "$LATEST_PIPELINE_ID" ] || [ "$LATEST_PIPELINE_ID" != "$CI_PIPELINE_ID" ]; then
        echo "skip deploy: not latest pipeline after debounce (latest=$LATEST_PIPELINE_ID current=$CI_PIPELINE_ID)";
        exit 0;
      fi
    - rsync -avz --delete dist/ /nas/kjb_service/zm/pre-project/html/

# 非 protected 分支：push 时先做 build 校验（避免合并 pre 时出现 build 报错）
build_check:
  stage: build
  image: node:20-bullseye
  tags:
    - risk-monitor-frontend
  # 只在 push 时做构建校验，且排除 protected 分支与目标分支 pre
  only:
    - pushes
  except:
    - pre
    - protected_branches
  script:
    - node -v
    - npm -v
    - echo "cache dir sizes:"
    - du -sh "$CI_PROJECT_DIR/.npm" "$CI_PROJECT_DIR/.npm/_cacache" 2>/dev/null || true
    - echo "=== npm ci start ==="
    - date -Iseconds
    - npm ci --cache "$CI_PROJECT_DIR/.npm" --no-audit --no-fund --include=optional --loglevel=verbose --timing --foreground-scripts
    - echo "=== npm ci end ==="
    - date -Iseconds
    - npm run build