# Stage 1: Build
FROM node:22.12-alpine AS build

# Install pnpm first (as root, since we need it globally)
RUN npm install -g pnpm

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -u 1001 -S modernmermaid -G nodejs

# Set working directory
WORKDIR /app

# Copy package files (as root, but will change ownership next)
COPY package.json pnpm-lock.yaml ./

# Change ownership to non-root user *before* installing deps
RUN chown -R modernmermaid:nodejs .

# Switch to non-root user for all subsequent steps
USER modernmermaid

# Install dependencies (now as non-root)
RUN pnpm install --frozen-lockfile

# Copy source code (still as non-root)
COPY --chown=modernmermaid:nodejs . .

# Build the app (TypeScript writes to node_modules/.tmp — now allowed)
RUN pnpm build


# Stage 2: Production
FROM node:22.12-alpine AS production

# Create non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -u 1001 -S modernmermaid -G nodejs

WORKDIR /app

# Install serve
RUN npm install -g serve

# Copy built files from build stage
COPY --from=build --chown=modernmermaid:nodejs /app/dist ./dist

USER modernmermaid

EXPOSE 3000

CMD ["serve", "-s", "dist", "-l", "3000"]