FROM node:lts-alpine3.22 AS base
HEALTHCHECK --interval=5s --timeout=10s --start-period=5s --retries=5 \
  CMD sh -c 'wget --no-verbose --tries=1 --spider http://127.0.0.1:3333 || exit 1'

# All deps stage
FROM base AS deps
WORKDIR /app/backend
ADD package.json package-lock.json ./
RUN npm ci

FROM deps AS develop
WORKDIR /app/backend
COPY dev-entrypoint.sh /entrypoint.sh
COPY .env.example /app/backend/.env
RUN chmod +x /entrypoint.sh
ENV NODE_ENV=development
EXPOSE 3333
ENTRYPOINT [ "/entrypoint.sh" ]

# Production only deps stage
FROM base AS production-deps
WORKDIR /app/backend
ADD package.json package-lock.json ./
RUN npm ci --omit=dev

# Build stage
FROM base AS build
WORKDIR /app/backend
COPY --from=deps /app/backend/node_modules /app/backend/node_modules
ADD . .
RUN node ace build

# Production stage
FROM base
ENV NODE_ENV=production
WORKDIR /app
COPY --from=production-deps /app/backend/node_modules /app/backend/node_modules
COPY --from=build /app/backend/build /app
EXPOSE 8080

CMD ["node", "./bin/server.js"]
