# ============================================
# STAGE 1: BUILDER STAGE
# ============================================
FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
COPY .npmrc ./
COPY prisma ./prisma/

# npm ci can exit 0 on some Docker Desktop setups while leaving node_modules/.bin
# empty ("Exit handler never called!") — then `prisma` / `nest` are "not found".
RUN npm ci --no-audit --no-fund || true; \
    if [ ! -e node_modules/.bin/prisma ] || [ ! -e node_modules/.bin/nest ]; then \
      echo "Incomplete npm ci (missing .bin links) — falling back to npm install"; \
      rm -rf node_modules; \
      npm install --no-audit --no-fund; \
    fi; \
    test -e node_modules/.bin/prisma; \
    test -e node_modules/.bin/nest

COPY . .

RUN npm run prisma:generate
RUN npm run build
RUN npm prune --omit=dev


# ============================================
# STAGE 2: PRODUCTION STAGE
# ============================================
FROM node:20-alpine

RUN apk add --no-cache dumb-init

WORKDIR /app

RUN addgroup -g 1001 -S nodejs && \
    adduser -S dyolink -u 1001

# Prisma client comes from the builder (npm prune --production keeps @prisma/client).
COPY package*.json ./
COPY prisma ./prisma/

COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules

COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

RUN mkdir -p /app/logs && \
    chown -R dyolink:nodejs /app

USER dyolink

EXPOSE 3000

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD node -e "require('http').get('http://127.0.0.1:3000/api/health', (r) => {if(r.statusCode!==200)process.exit(1)})"

ENTRYPOINT ["dumb-init", "--", "docker-entrypoint.sh"]

CMD ["node", "dist/src/main.js"]
