FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN --mount=type=cache,target=/root/.npm npm ci

COPY . .
ARG BUILD_SHA=unknown
ENV BUILD_SHA=$BUILD_SHA
RUN npm run build

FROM node:20-alpine AS production

# Optional mirror for Alpine packages (helps avoid transient I/O errors on dl-cdn)
ARG ALPINE_MIRROR=
RUN if [ -n "$ALPINE_MIRROR" ]; then sed -i "s|dl-cdn.alpinelinux.org|$ALPINE_MIRROR|g" /etc/apk/repositories; fi

WORKDIR /app

COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/shared ./shared
COPY --from=builder /app/drizzle.config.ts ./drizzle.config.ts
COPY --from=builder /app/docker-entrypoint.sh ./docker-entrypoint.sh
COPY --from=builder /app/scripts ./scripts
COPY --from=builder /app/server/scripts ./server/scripts

RUN chmod +x docker-entrypoint.sh
RUN mkdir -p /app/data

# VPN client apps (olcbox APK/IPA)
COPY --from=builder /app/apps /app/apps

# Python + python-docx для обработки DOCX-шаблонов
RUN apk add --no-cache python3 py3-pip py3-lxml \
    && pip3 install --break-system-packages python-docx \
    && rm -rf /root/.cache/pip

EXPOSE 5000

HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
  CMD wget -qO- http://localhost:5000/api/health || exit 1

COPY --from=builder /app/migrations ./migrations
ENTRYPOINT ["./docker-entrypoint.sh"]

