# Base image with PNPM:
ARG NODE_VERSION=24.4.1
FROM node:${NODE_VERSION}-slim AS base
WORKDIR /app
RUN npm install -g pnpm

# Build stage:
FROM base AS builder

COPY . .

# Create .npmrc with build-time token for private packages:
ARG NPM_TOKEN
RUN echo "@percepta:registry=https://registry.npmjs.org/" > .npmrc && \
    echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> .npmrc

# Add BASE_PATH as a build argument
ARG BASE_PATH
ENV BASE_PATH=${BASE_PATH}

RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile

RUN NODE_ENV=production NODE_OPTIONS="--max-old-space-size=4096" pnpm build

# Remove .npmrc for security (contains auth token):
RUN rm -f .npmrc

# Production stage - create the final image:
FROM base AS production

# Install PostgreSQL client:
USER root
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# Set production environment:
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Copy BASE_PATH from the builder stage
ENV BASE_PATH=${BASE_PATH}

# Copy built app from builder stage
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public

# Copy scripts and source files needed for start.sh and runtime
COPY --from=builder /app/scripts ./scripts
COPY --from=builder /app/src ./src
COPY --from=builder /app/node_modules ./node_modules


# Expose the port:
EXPOSE 3000

# Set correct permissions and user:
RUN chown -R 1000:1000 /app && chmod +x /app/scripts/start.sh
USER 1000

# Start the application:
CMD ["./scripts/start.sh"]
