# syntax=docker/dockerfile:1

# ============================================================================
# Builder stage
# ============================================================================
FROM node:22.11.0-slim AS builder

RUN npm install -g corepack@latest && corepack enable

WORKDIR /app

# Copy all package manifests so pnpm can resolve the workspace lockfile,
# but use --ignore-scripts to skip buttplug's Rust/WASM build entirely.
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./
COPY packages/backend/package.json ./packages/backend/package.json
COPY packages/frontend/package.json ./packages/frontend/package.json
COPY packages/buttplug/package.json ./packages/buttplug/package.json

RUN pnpm install --frozen-lockfile --filter @sexy.pivoine.art/backend --ignore-scripts

# Only rebuild the native argon2 binding — not buttplug or anything else
RUN pnpm rebuild argon2

COPY packages/backend ./packages/backend

RUN pnpm --filter @sexy.pivoine.art/backend build

RUN CI=true pnpm install --frozen-lockfile --filter @sexy.pivoine.art/backend --prod --ignore-scripts

RUN pnpm rebuild argon2

# ============================================================================
# Runner stage
# ============================================================================
FROM node:22.11.0-slim AS runner

RUN apt-get update && apt-get install -y \
    dumb-init \
    ffmpeg \
    wget \
    && rm -rf /var/lib/apt/lists/*

RUN userdel -r node && \
    groupadd -r -g 1000 node && \
    useradd -r -u 1000 -g node -m -d /home/node -s /bin/bash node

WORKDIR /home/node/app

RUN mkdir -p packages/backend

COPY --from=builder --chown=node:node /app/node_modules ./node_modules
COPY --from=builder --chown=node:node /app/package.json ./package.json
COPY --from=builder --chown=node:node /app/packages/backend/dist ./packages/backend/dist
COPY --from=builder --chown=node:node /app/packages/backend/node_modules ./packages/backend/node_modules
COPY --from=builder --chown=node:node /app/packages/backend/package.json ./packages/backend/package.json
COPY --from=builder --chown=node:node /app/packages/backend/src/migrations ./packages/backend/migrations

RUN mkdir -p /data/uploads && chown node:node /data/uploads

USER node

ENV NODE_ENV=production \
    PORT=4000

EXPOSE 4000

HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:4000/health

ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "packages/backend/dist/index.js"]
