# Stage 1: Build
FROM node:20-alpine AS builder

# Enable pnpm via corepack
RUN corepack enable && corepack prepare pnpm@latest --activate

WORKDIR /workspace

# Copy workspace manifests first for dependency caching
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml nx.json tsconfig.base.json ./

# Copy frontend app files
COPY apps/frontend ./apps/frontend

# Install all dependencies (frozen for reproducibility)
RUN pnpm install --frozen-lockfile

# Build the frontend
RUN pnpm nx run frontend:build --configuration=production

# Stage 2: Serve with nginx
FROM nginx:1.27-alpine AS runner

# Copy built assets
COPY --from=builder /workspace/dist/apps/frontend /usr/share/nginx/html

# Copy nginx config
COPY apps/frontend/nginx.conf /etc/nginx/conf.d/default.conf

# Create non-root user
RUN addgroup -S citygame && adduser -S citygame -G citygame

EXPOSE 80

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- http://localhost:80/healthz || exit 1

CMD ["nginx", "-g", "daemon off;"]
