# 多阶段构建 Vue 3 前端镜像

###############################################################################
# Stage 1: Builder - 构建前端资源
###############################################################################
# 构建参数 - 镜像缓存服务器
ARG REGISTRY_CACHE=

FROM ${REGISTRY_CACHE}library/node:20-alpine as builder

# 构建参数
ARG NPM_REGISTRY=https://registry.npmmirror.com
ARG VERSION=dev
ARG BUILD_DATE

# 设置工作目录
WORKDIR /app

# 配置 Alpine 镜像源为中科大（加速下载）
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories

# 配置 npm 镜像源（淘宝镜像）
RUN npm config set registry ${NPM_REGISTRY}

# 复制依赖文件
COPY package*.json ./

# 安装依赖 (使用 BuildKit 缓存挂载加速)
RUN --mount=type=cache,target=/root/.npm \
    npm ci --prefer-offline --no-audit

# 复制源代码
COPY . .

# 构建生产版本
RUN npm run build

# 列出构建产物 (用于调试)
RUN ls -la /app/dist

###############################################################################
# Stage 2: Runtime - Nginx 静态文件服务
###############################################################################
ARG REGISTRY_CACHE=

FROM ${REGISTRY_CACHE}library/nginx:alpine as runtime

# 元数据标签
ARG VERSION=dev
ARG BUILD_DATE
LABEL org.opencontainers.image.title="FastAPI Template Frontend" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.description="FastAPI enterprise template frontend"

# 从 builder 复制构建产物
COPY --from=builder /app/dist /usr/share/nginx/html

# 复制 Nginx 配置
COPY nginx.conf /etc/nginx/conf.d/default.conf

# 创建非 root 用户 (Nginx alpine 镜像已有 nginx 用户)
# 修改文件权限
RUN chown -R nginx:nginx /usr/share/nginx/html && \
    chmod -R 755 /usr/share/nginx/html

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost:80/ || exit 1

# 暴露端口
EXPOSE 80

# 启动 Nginx
CMD ["nginx", "-g", "daemon off;"]
