# ===== 前端构建阶段 =====
FROM node:20-alpine AS frontend-builder

WORKDIR /app

# 安装pnpm
RUN npm install -g pnpm@9

# 复制package文件
COPY package.json pnpm-workspace.yaml turbo.json ./
COPY apps ./apps
COPY packages ./packages
COPY internal ./internal
COPY scripts ./scripts

# 安装依赖（如果存在lock文件则使用）
RUN pnpm install --no-frozen-lockfile

# 构建前端
RUN pnpm build

# ===== 后端构建阶段 =====
FROM frontend-builder AS backend-builder

WORKDIR /app

# 后端依赖已经在前端构建阶段安装完成
# 构建后端（如果需要）
WORKDIR /app/apps/backend
RUN pnpm build || echo "No build script or build not needed"

# ===== Nginx + Node.js 运行阶段 =====
FROM node:20-alpine AS runner

WORKDIR /app

# 安装nginx和supervisord
RUN apk add --no-cache nginx supervisor

# 安装pnpm
RUN npm install -g pnpm@9

# 从构建阶段复制前端产物
COPY --from=frontend-builder /app/apps/web-antd/dist /usr/share/nginx/html

# 从构建阶段复制后端代码和依赖
COPY --from=backend-builder /app/apps/backend /app/backend
COPY --from=backend-builder /app/node_modules /app/node_modules

# 创建nginx配置和日志目录
RUN mkdir -p /run/nginx && \
    mkdir -p /var/log/supervisor && \
    mkdir -p /var/log/nginx && \
    mkdir -p /var/log/backend

# 复制nginx配置
COPY docker/nginx.conf /etc/nginx/nginx.conf

# 复制supervisor配置
COPY docker/supervisord.conf /etc/supervisord.conf

# 暴露端口
EXPOSE 80 3000

# 启动supervisor管理nginx和backend
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisord.conf"]
