FROM node:22-alpine AS build-base
RUN npm install -g npm@11.16.0 --no-audit --no-fund

FROM build-base AS api-builder
WORKDIR /app
COPY listify-api/package*.json ./
RUN npm ci --no-audit --no-fund
COPY listify-api/ ./
RUN npm run build

FROM build-base AS web-builder
WORKDIR /app
COPY listify-client/package*.json ./
RUN npm ci --no-audit --no-fund
COPY listify-client/ ./
RUN npm run build

FROM node:22-alpine AS runtime
RUN apk add --no-cache nginx \
    && rm -rf /usr/local/lib/node_modules/npm \
    && rm -f /usr/local/bin/npm /usr/local/bin/npx

ENV NODE_ENV=production
ENV PORT=3000

WORKDIR /app
COPY --from=api-builder /app/dist ./dist
COPY --from=api-builder /app/src/mail/templates ./dist/mail/templates

COPY --from=web-builder /app/dist/listify-client/browser /usr/share/nginx/html
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/start.sh /usr/local/bin/start-listify

RUN chmod +x /usr/local/bin/start-listify

EXPOSE 80

CMD ["/usr/local/bin/start-listify"]
