stages:
  - build
  - test
  - report

# 全局变量
variables:
  CYPRESS_baseUrl: "http://localhost:3000"
  NODE_VERSION: "16-alpine"
  CYPRESS_IMAGE: "cypress/browsers:node16.14.2-slim-chrome103-ff102"

# 1. 构建阶段
build:
  stage: build
  image: node:$NODE_VERSION
  script:
    - npm ci --cache .npm --prefer-offline
    - npm run build
  artifacts:
    paths:
      - dist/
      - node_modules/
    expire_in: 1 hour
  cache:
    paths:
      - .npm/
      - node_modules/
  only:
    - web
    - projects
    - merge_requests

# 2. 基础测试
test:basic:
  stage: test
  image: $CYPRESS_IMAGE
  dependencies:
    - build
  script:
    # 清理可能存在的旧文件
    - rm -rf cypress/reports/* cypress/videos/* cypress/screenshots/* || true
    - npm run preview -- --host 0.0.0.0 --port 3000 &
    - npx wait-on http://localhost:3000
    - npx cypress run --browser chrome --spec "cypress/e2e/spec.cy.js" --reporter mochawesome --reporter-options "reportDir=cypress/reports/basic,overwrite=false,html=true,json=true"
  artifacts:
    when: always
    paths:
      - cypress/reports/
      - cypress/videos/
      - cypress/screenshots/
    expire_in: 1 week
  only:
    - web
    - projects
    - merge_requests

# 3. 生成测试报告
report:
  stage: report
  image: node:$NODE_VERSION
  dependencies:
    - test:basic
  script:
    - npm install -g mochawesome-merge mochawesome-report-generator
    - mkdir -p public/reports
    - mochawesome-merge "cypress/reports/**/*.json" > public/reports/merged-report.json
    - marge public/reports/merged-report.json --reportDir public/reports --inline --reportTitle "DC-TOM Cypress 测试报告"
    - cp -r cypress/videos public/ || echo "无视频文件"
    - cp -r cypress/screenshots public/ || echo "无截图文件"
  artifacts:
    paths:
      - public/
    expire_in: 1 week
  only:
    - web
    - projects
    - merge_requests

# GitLab Pages 部署
pages:
  stage: report
  dependencies:
    - report
  script:
    - echo "部署测试报告到 GitLab Pages"
  artifacts:
    paths:
      - public/
  only:
    - projects
