# Staging replica of the VM: production builds of both frontend and backend,
# NODE_ENV=dev_stage (verbose logging + source maps for debuggability), behind
# nginx — exactly like the deployed VM. nginx (8080) routes `/` to the frontend
# (vite preview, 3001) and `/api` to the backend (compiled, 3000 in dev_stage).
# dev_stage forces secure cookies, so run this behind HTTPS (e.g. a tunnel).

# --- Frontend build (production) ---
FROM node:24-alpine AS frontend-builder
RUN apk add --no-cache git
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci
COPY frontend .
RUN npm run build

# --- Backend build (TypeScript -> dist; bcrypt compiles natively) ---
FROM node:24-alpine AS backend-builder
RUN apk add --no-cache python3 make g++
WORKDIR /app/backend
COPY backend/package.json backend/package-lock.json ./
RUN npm ci
COPY backend .
RUN npm run build && npm prune --omit=dev

# --- Runtime: nginx + compiled backend (3000) + frontend prod preview (3001) ---
FROM node:24-alpine
RUN apk add --no-cache nginx
ENV NODE_ENV=dev_stage
ENV FRONT_PORT=3001

# Backend: compiled output + production-only deps (no native recompile here).
WORKDIR /app/backend
COPY --from=backend-builder /app/backend/node_modules ./node_modules
COPY --from=backend-builder /app/backend/dist ./dist
COPY --from=backend-builder /app/backend/package.json ./package.json

# Frontend: built assets + deps/config needed to serve them via `vite preview`.
WORKDIR /app/frontend
COPY --from=frontend-builder /app/frontend/node_modules ./node_modules
COPY --from=frontend-builder /app/frontend/dist ./dist
COPY --from=frontend-builder /app/frontend/package.json ./package.json
COPY --from=frontend-builder /app/frontend/vite.config.ts ./vite.config.ts

COPY nginx.conf /etc/nginx/nginx.conf
COPY 502.html /usr/share/nginx/html/502.html
RUN chown nginx:nginx /usr/share/nginx/html/502.html && \
    chmod 644 /usr/share/nginx/html/502.html

EXPOSE 8080

# Backend (migrate + seed + serve on 3000), frontend preview (3001), nginx (8080).
CMD ["sh", "-c", "(cd /app/backend && npm run start:production) & (cd /app/frontend && npm run start) & nginx -g 'daemon off;'"]
