# ===============================
# ① 构建阶段：安装依赖 + 拷贝代码
# ===============================
FROM docker.1ms.run/node:20-slim AS build

WORKDIR /app

# 安装顶层依赖（如果有前端构建）

# 再复制源码（包括前端项目）
RUN npm config set registry https://registry.npmmirror.com
 COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# 拷贝前端、后端、静态资源

# 可选：前端构建（如果你有 vite、react、vue 项目）
# RUN npm run build

# ===============================
# ② 后端依赖安装阶段
# ===============================
FROM docker.1ms.run/node:20-slim AS server_deps

WORKDIR /app/server
COPY server/package*.json ./
RUN if [ -f package.json ]; then npm ci --omit=dev; fi

# ===============================
# ③ 运行阶段（Nginx + Node 同容器）
# ===============================
FROM docker.1ms.run/nginx:1.27-alpine

# 安装 Node.js（给后端运行）
# 更换为国内源（清华或阿里云）
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories \
    && apk update \
    && apk add --no-cache nodejs npm bash

WORKDIR /app

# 拷贝后端代码和依赖
COPY --from=build /app/server /app/server
COPY --from=server_deps /app/server/node_modules /app/server/node_modules

# 拷贝前端静态资源
COPY --from=build /app/dist /usr/share/nginx/html
COPY --from=build /app/public /usr/share/nginx/html/public
COPY --from=build /app/index.html /usr/share/nginx/html/

# 拷贝 Nginx 配置和启动脚本
COPY nginx.conf /etc/nginx/nginx.conf
COPY start.sh /start.sh
RUN chmod +x /start.sh

EXPOSE 80
CMD ["/start.sh"]
