# syntax=docker/dockerfile:1.7-labs

ARG NODE_IMAGE=node:24-alpine
ARG PNPM_VERSION=10.20.0

########################
# 0) Base común
########################
FROM ${NODE_IMAGE} AS base
ENV CI=1 \
    NODE_ENV=production
RUN corepack enable && corepack prepare pnpm@${PNPM_VERSION} --activate

WORKDIR /repo

########################
# 1) Turborepo prune (reduce contexto)
########################
FROM base AS pruner

# Copiar archivos raíz necesarios
COPY turbo.json package.json pnpm-workspace.yaml pnpm-lock.yaml ./

# Copiar los directorios relevantes del monorepo
COPY packages ./packages
COPY apps ./apps
COPY modules ./modules

# Ejecuta prune para @erp/factuges-server
RUN npx --yes turbo@2.5.8 prune @erp/factuges-server --docker

########################
# 2) Builder: código + link deps y build
########################
FROM base AS builder

# Copiamos todo lo “pruned” (json, lock, full)
COPY --from=pruner /repo/out/full/ ./
COPY --from=pruner /repo/out/pnpm-lock.yaml ./pnpm-lock.yaml

# Reutilizamos la store prefetch
#COPY --from=installer /root/.local/share/pnpm/store /root/.local/share/pnpm/store

# Instalamos solo lo necesario para prod de los workspaces
RUN pnpm install --frozen-lockfile --prefer-offline

# IMPORTANTE: build de paquetes buildables (utils, logger, etc.) primero
# Turborepo asegura orden con "dependsOn". Un único comando:
RUN pnpm -w turbo run build --filter=@erp/factuges-server...

########################
# 3) Runner minimal
########################
#FROM ${NODE_IMAGE} AS runner
FROM base AS runner
ENV NODE_ENV=production TZ=UTC

# Don't run production as root
RUN addgroup --system --gid 1001 expressjs
RUN adduser --system --uid 1001 expressjs
USER expressjs

#COPY --from=builder /repo .
COPY --from=builder /repo/node_modules ./node_modules
COPY --from=builder /repo/packages ./packages
COPY --from=builder /repo/package.json ./package.json
COPY --from=builder /repo/pnpm-lock.yaml ./pnpm-lock.yaml
COPY --from=builder /repo/pnpm-workspace.yaml ./pnpm-workspace.yaml

COPY --from=builder /repo/apps/server/dist ./apps/server/dist
COPY --from=builder /repo/apps/server/.env.production ./apps/server/dist/.env
COPY --from=builder /repo/apps/server/node_modules ./apps/server/node_modules
COPY --from=builder /repo/apps/server/package.json ./apps/server/package.json


# Salud del contenedor (ajusta puerto/endpoint)
#HEALTHCHECK --interval=20s --timeout=3s --retries=5 \
# CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3002)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

EXPOSE 3002
#CMD ["pnpm","exec", "node", "--env-file=apps/server/dist/.env", "apps/server/dist/index.js"]
CMD ["pnpm","exec", "node", "apps/server/dist/index.js"]
