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:
    - docker
    - frontend
    - linux
  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:
    - docker
    - frontend
    - linux
  only:
    - pre
  dependencies:
    - build_pre
  script:
    - apk add --no-cache rsync
    - test -d dist || (echo "dist not found" && exit 1)
    - test -d /nas/kjb_service/zm/pre-project/html || (echo "deploy target path not found" && exit 1)
    - 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:
    - docker
    - frontend
    - linux
  # 只在 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