# syntax=docker/dockerfile:1

# ============================================
# MARINA - Docker image
# Multi-stage build optimized for production
# Base image uses Node 22 Alpine for small footprint
# pnpm is explicitly installed as requested
# Final image is tagged under cristianmi2404/*
# ============================================

# ---- Base stage with pnpm ----
FROM node:22-alpine AS base

# Install pnpm globally (explicit as requested)
RUN npm install -g pnpm@9

WORKDIR /app

# ---- Dependencies stage ----
FROM base AS deps

# Copy only manifests first for better layer caching
COPY package.json pnpm-lock.yaml ./

# Install ALL dependencies (including dev) for build
RUN pnpm install --frozen-lockfile

# ---- Builder stage ----
FROM base AS builder

# Copy node_modules from deps stage
COPY --from=deps /app/node_modules ./node_modules

# Copy the rest of the source
COPY . .

# Build the application:
# - Vite builds the React frontend to dist/
# - esbuild bundles the Express server to dist/server.cjs
RUN pnpm build

# ---- Production dependencies (pruned) ----
FROM base AS prod-deps

COPY package.json pnpm-lock.yaml ./

# Install ONLY production dependencies
RUN pnpm install --frozen-lockfile --prod

# ---- Final runtime stage (small & secure) ----
FROM node:22-alpine AS runner

WORKDIR /app

# Set production environment
ENV NODE_ENV=production
ENV PORT=3000

# Create non-root user for security (node user already exists in the image)
USER node

# Copy only the artifacts needed to run
COPY --from=builder --chown=node:node /app/dist ./dist
COPY --from=builder --chown=node:node /app/assets ./assets
COPY --from=builder --chown=node:node /app/index.html ./
COPY --from=builder --chown=node:node /app/metadata.json ./
COPY --from=prod-deps --chown=node:node /app/node_modules ./node_modules
COPY --chown=node:node package.json ./

# Expose the port the server listens on
EXPOSE 3000

# Healthcheck (optional but recommended)
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD node -e "const http = require('http'); http.get('http://localhost:3000', (res) => { process.exit(res.statusCode === 200 ? 0 : 1); }).on('error', () => process.exit(1));"

# Start the production server
CMD ["node", "dist/server.cjs"]
