FROM node:22-bookworm-slim AS build

RUN npm install --global pnpm@9.15.4
WORKDIR /app

COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY client/package.json ./client/package.json
RUN pnpm install --frozen-lockfile

COPY nest-cli.json tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN pnpm run build

FROM node:22-bookworm-slim AS runtime

ENV NODE_ENV=production
ENV SKIN_GENERATION_PYTHON=/opt/skin-generation-venv/bin/python
ENV PIP_INDEX_URL=https://mirrors.cloud.tencent.com/pypi/simple

RUN sed -i 's|deb.debian.org|mirrors.cloud.tencent.com|g' /etc/apt/sources.list.d/debian.sources \
    && apt-get update \
    && apt-get install --yes --no-install-recommends ca-certificates python3 python3-venv \
    && rm -rf /var/lib/apt/lists/*

RUN npm install --global pnpm@9.15.4
WORKDIR /app

COPY requirements-skin-generation.txt ./
RUN python3 -m venv /opt/skin-generation-venv \
    && /opt/skin-generation-venv/bin/pip install --no-cache-dir --requirement requirements-skin-generation.txt

COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY client/package.json ./client/package.json
RUN pnpm install --prod --frozen-lockfile && pnpm store prune

COPY --from=build /app/dist ./dist
COPY scripts ./scripts

RUN mkdir -p config generated/account-assets generated/skins logs redis-data \
    && chown -R node:node /app

USER node
EXPOSE 3000 3001
HEALTHCHECK --interval=15s --timeout=5s --start-period=30s --retries=4 \
  CMD node -e "fetch('http://127.0.0.1:3000/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))"

CMD ["node", "dist/main.js"]
