# 使用 Node.js 18 基础镜像 (Debian bullseye)
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"
# 添加 esbuild 镜像源
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 ./

# 1. 显式安装 esbuild 二进制
RUN npm install @esbuild/linux-x64 --verbose --registry=https://registry.npmmirror.com

# 2. 安装其他原生模块
RUN npm install canvas@2.11.2 --verbose --ignore-scripts
RUN npm install sharp@0.32.6 --verbose --ignore-scripts

# 3. 安装项目依赖（移除 --no-optional）
RUN npm install --verbose --registry=https://registry.npmmirror.com

# 4. 验证 esbuild 安装
RUN ls -la node_modules/esbuild/bin && \
    ./node_modules/.bin/esbuild --version

# 复制源码并构建
COPY . .
RUN npm run build:dev

# 生产阶段
FROM docker.m.daocloud.io/library/nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

# 设置时区
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

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