# Build stage - clone from GitHub and build
FROM node:22-alpine AS builder

WORKDIR /app

# Install git for cloning
RUN apk add --no-cache git

# Clone repository (use ARG for flexibility)
ARG REPO_URL=https://github.com/your-username/your-repo.git
ARG BRANCH=main
RUN git clone --branch ${BRANCH} --depth 1 ${REPO_URL} .

# Install dependencies
RUN npm install --legacy-peer-deps && \
  npm cache clean --force

# Build app with sufficient memory
RUN NODE_OPTIONS="--max-old-space-size=2048" npm run build

# Runtime stage
FROM node:22-alpine

WORKDIR /app

# Install git for potential runtime needs
RUN apk add --no-cache git

# Copy package files from builder
COPY --from=builder /app/package.json /app/package-lock.json ./

# Install production dependencies only
RUN npm install --omit=dev --legacy-peer-deps && \
  npm cache clean --force && \
  rm -rf /root/.npm /root/.cache

# Copy built app from builder
COPY --from=builder /app/.output ./.output

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

EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/', (r) => {if (r.statusCode !== 200) throw new Error(r.statusCode)})"

# Start app
CMD ["node", "--max-old-space-size=512", ".output/server/index.mjs"]
