# Optimized Dockerfile for backend and fallback-ui services (project root)

# 1. ---- Base Bun image
FROM oven/bun:1.3.10 AS base
WORKDIR /app

# 2. ---- Pruner ----
FROM base AS pruner
WORKDIR /app
# Copy config files first for better caching
COPY package.json  turbo.json ./
COPY apps/backend/package.json ./apps/backend/
COPY apps/fallback-ui/package.json ./apps/fallback-ui/
COPY packages/shared/     ./packages/shared
COPY packages/ui/package.json ./packages/ui/
RUN bun install -g turbo
COPY . .
RUN turbo prune --scope=backend --scope=fallback-ui --scope=@packages/shared --docker
# RUN find . -path "./node_modules" -prune -o -print

# 3. ---- Builder ----
FROM base AS builder
WORKDIR /app
# Copy package files first to cache bun install
COPY --from=pruner /app/out/json/ .
#COPY --from=pruner /app/out/bun.lock ./bun.lock
#RUN cat ./bun.lock
COPY --from=pruner /app/turbo.json .
RUN bun install
# Copy source code after dependencies are installed
COPY --from=pruner /app/out/full/ .
RUN bunx turbo run build --filter=fallback-ui... --filter=backend...
RUN find . -path "./node_modules" -prune -o -print

# 4. ---- Runner ----
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
# Copy package files and install production deps
COPY --from=pruner /app/out/json/ .
#COPY --from=pruner /app/out/bun.lock ./bun.lock
RUN bun install --production
# Copy built applications
COPY --from=builder /app/apps/backend/dist ./apps/backend/dist
COPY --from=builder /app/apps/fallback-ui/dist ./apps/fallback-ui/dist
COPY --from=builder /app/packages/shared ./packages/shared

# RUN ls -R
RUN find . -path "./node_modules" -prune -o -print

EXPOSE 4000
CMD ["bun", "apps/backend/dist/apps/backend/index.js"]
