# Stage 1: Build the TypeScript application
FROM node:20-alpine AS build

WORKDIR /usr/src/app

# Copy package.json and package-lock.json first to leverage Docker cache
COPY package.json package-lock.json ./
RUN npm install

# Copy the rest of the application source code
COPY . .
# Removed: RUN mkdir -p public/app - No longer needed as public/app will be copied directly in Stage 2

# Build TypeScript to JavaScript
RUN npm run build

# 全局安装 PM2 用于进程管理
RUN npm install -g pm2

# Stage 2: Run the application
FROM node:20-alpine

WORKDIR /usr/src/app

# 复制构建阶段的 artifact
COPY --from=build /usr/src/app/dist ./dist
COPY --from=build /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/package.json ./package.json
COPY --from=build /usr/src/app/ecosystem.config.js ./ecosystem.config.js
COPY --from=build /usr/src/app/public ./public

# 全局安装 PM2 用于进程管理
RUN npm install -g pm2

# 创建日志目录 (确保容器内路径存在且可写)
RUN mkdir -p /app/logs/coloring
# 设置日志目录权限 (例如，给 node 用户)
# Node.js 官方 alpine 镜像通常以 'node' 用户运行，UID 通常为 1000
RUN chown -R node:node /app/logs/coloring
USER node # 以非 root 用户运行应用

# 暴露应用程序监听的端口
EXPOSE 3000
EXPOSE 3001

# 定义容器启动命令
CMD ["pm2-runtime", "ecosystem.config.js"]