# ── Stage 1: base ────────────────────────────────────────────
# Shared foundation: system deps + pnpm + lockfile-only install
FROM node:20-alpine3.19 AS base
WORKDIR /usr/src/app
RUN apk add --no-cache dumb-init curl git
RUN npm install -g pnpm
COPY ["package.json", "pnpm-lock.yaml", "./"]
RUN pnpm install --frozen-lockfile
COPY src/templates ./src/templates

# ── Stage 2: build ───────────────────────────────────────────
# Compile TypeScript → dist/
FROM base AS build
COPY . .
RUN pnpm build
COPY src/templates ./dist/templates

# ── Stage 3: production-deps ─────────────────────────────────
# Prune to prod-only dependencies (no devDeps)
FROM base AS production-deps
RUN pnpm install --frozen-lockfile --prod

# ── Stage 4: development ─────────────────────────────────────
FROM base AS development
ENV NODE_ENV=development
RUN chown -R node:node /usr/src/app
USER node
EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:3001/health || exit 1
ENTRYPOINT ["dumb-init", "--"]
CMD ["pnpm", "dev"]

# ── Stage 5: production ──────────────────────────────────────
FROM node:20-alpine3.19 AS production
RUN apk add --no-cache dumb-init curl
RUN addgroup -g 1001 -S appgroup && adduser -S appuser -u 1001 -G appgroup
WORKDIR /usr/src/app
ENV TZ="Asia/Ho_Chi_Minh"
ENV NODE_ENV=production
# Reuse pruned deps from production-deps stage (no re-install)
COPY --from=production-deps /usr/src/app/node_modules ./node_modules
COPY --from=production-deps /usr/src/app/package.json ./package.json
COPY --from=build /usr/src/app/dist ./dist
COPY --from=build /usr/src/app/lib ./lib
COPY --from=build /usr/src/app/src/templates ./src/templates
RUN mkdir -p storage/swagger storage/logs storage/uploads && chown -R appuser:appgroup storage
USER appuser
EXPOSE 3001
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:3001/health || exit 1
ENTRYPOINT ["dumb-init", "--"]
CMD ["node", "dist/index.js"]
