FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
RUN npm ci

COPY . .
RUN npm run prisma:generate -w apps/api
RUN npm run build -w apps/api

FROM node:20-alpine AS runner

WORKDIR /app
ENV NODE_PATH=/app/apps/api/node_modules
ENV PORT=3000

COPY package*.json ./
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
RUN npm ci --omit=dev

COPY --from=builder /app/apps/api/dist ./apps/api/dist
COPY --from=builder /app/apps/api/prisma ./apps/api/prisma

VOLUME ["/app/apps/api/uploads"]

EXPOSE 3000

# During initial setup we use `prisma db push` at container start to bypass baseline migration issues.
CMD ["npm", "run", "start:docker", "-w", "apps/api"]