FROM node:20.18.3-alpine AS builder

WORKDIR /app

COPY package.json ./

RUN npm config set registry https://registry.npmmirror.com \
    && npm install

COPY . .

RUN npm run build \
    && test -f /app/dist/build/h5/index.html

FROM nginx:1.29-alpine

# 清除 Nginx 自带欢迎页，只保留本次构建的 H5 静态文件。
RUN rm -rf /usr/share/nginx/html/*

COPY --from=builder /app/dist/build/h5/ /usr/share/nginx/html/

# 直接生成与原 static.json 核心规则等价的 Nginx 配置：
# 1. 监听线上服务使用的 5000 端口。
# 2. 支持外层代理保留或剥离 /h5 前缀。
# 3. 未匹配的页面路由统一回退到 index.html。
# 4. index.html 禁用缓存，避免发布后继续读取旧页面。
RUN test -f /usr/share/nginx/html/index.html \
    && printf '%s\n' \
    'server {' \
    '    listen 5000;' \
    '    listen [::]:5000;' \
    '    server_name _;' \
    '' \
    '    root /usr/share/nginx/html;' \
    '    index index.html;' \
    '' \
    '    location = /h5 {' \
    '        return 301 /h5/;' \
    '    }' \
    '' \
    '    location = /h5/ {' \
    '        rewrite ^ /index.html last;' \
    '    }' \
    '' \
    '    location /h5/ {' \
    '        rewrite ^/h5/(.*)$ /$1 last;' \
    '    }' \
    '' \
    '    location / {' \
    '        try_files $uri $uri/ /index.html;' \
    '    }' \
    '' \
    '    location = /index.html {' \
    '        add_header Cache-Control "no-store, no-cache" always;' \
    '        try_files $uri =404;' \
    '    }' \
    '}' \
    > /etc/nginx/conf.d/default.conf

EXPOSE 5000

CMD ["nginx", "-g", "daemon off;"]
