FROM node:20.19-slim

# 安装系统依赖和工具
RUN apt-get update && apt-get install -y \
    curl \
    wget \
    procps \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this first prevents re-running npm install on every code change.
COPY package*.json ./

# Install dependencies
RUN yarn install --registry https://registry.npmmirror.com/ --ignore-engines

# Copy the rest of the application files to the container image.
COPY . .

# Build the application
RUN yarn run build

RUN echo "Debug: Contents of /app after build:"
RUN ls -la /app
RUN echo "Debug: Contents of /app/dist after build:"
RUN ls -la /app/dist || echo "Debug: /app/dist directory not found or ls failed"

# 创建非 root 用户
RUN groupadd -r nodeuser && useradd -r -g nodeuser nodeuser
RUN chown -R nodeuser:nodeuser /app
USER nodeuser

EXPOSE 3302

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
  CMD curl -f http://localhost:3302/ping || exit 1

CMD ["npm", "run", "start"]