FROM docker.m.daocloud.io/library/node:18-bullseye AS build

# 设置环境变量
ENV npm_config_canvas_binary_host_mirror="https://npmmirror.com/mirrors/canvas"
ENV npm_config_sharp_binary_host="https://npmmirror.com/mirrors/sharp"
ENV npm_config_sharp_libvips_binary_host="https://npmmirror.com/mirrors/sharp-libvips"
ENV ESBUILD_BINARY_HOST="https://npmmirror.com/mirrors/esbuild"

# 安装系统依赖
RUN sed -i 's/deb.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    sed -i 's/security.debian.org/mirrors.aliyun.com/g' /etc/apt/sources.list && \
    apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    python3 \
    pkg-config \
    libcairo2-dev \
    libpango1.0-dev \
    libjpeg-dev \
    libgif-dev \
    librsvg2-dev \
    libvips-dev \
    && rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 复制包管理文件
COPY package.json package-lock.json ./

# 解决 sharp 版本冲突
RUN npm install sharp@0.34.3 --verbose --registry=https://registry.npmmirror.com

# 安装项目依赖
RUN npm install --legacy-peer-deps --verbose --registry=https://registry.npmmirror.com

# 添加 crypto polyfill
RUN echo "globalThis.crypto = { getRandomValues: require('crypto').randomFillSync };" > crypto-polyfill.js

# 复制源码并构建
COPY . .
RUN NODE_OPTIONS="--require ./crypto-polyfill.js" npm run build:test -- --mode test

# 生产阶段
FROM docker.m.daocloud.io/library/nginx:alpine

# 设置时区
RUN echo "https://mirrors.aliyun.com/alpine/v3.22/main/" > /etc/apk/repositories && \
    echo "https://mirrors.aliyun.com/alpine/v3.22/community/" >> /etc/apk/repositories && \
    apk update && \
    apk add --no-cache tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

# 复制构建产物
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

EXPOSE 8333
CMD ["nginx", "-g", "daemon off;"]
