FROM oven/bun:1.2.18 AS builder
WORKDIR /build

# Copy the entire build context (which contains whatever project folders exist)
COPY . .

# Conditionally build website if present
RUN if [ -d "website" ]; then \
      cd website && bun install && bun run build && cd ..; \
    fi

# Conditionally build mobile if present
RUN if [ -d "mobile" ]; then \
      cd mobile && bun install && bun run build:web && cd ..; \
    fi

# Conditionally build games if present
RUN if [ -d "games" ]; then \
      cd games && bun install && bun run build && cd ..; \
    fi

FROM oven/bun:1.2.18
WORKDIR /app

# Copy backend configuration and install production dependencies
COPY backend/package.json backend/bun.lock backend/tsconfig.json ./
RUN bun install --frozen-lockfile --production

# Copy backend source code
COPY backend/src ./src

# Create public assets directories
RUN mkdir -p public public/mobile public/games

# Copy all build context to a temp folder in production stage to run conditional copies
COPY --from=builder /build /tmp/build

RUN if [ -d "/tmp/build/website/dist" ]; then cp -r /tmp/build/website/dist/* ./public/; fi
RUN if [ -d "/tmp/build/mobile/dist" ]; then cp -r /tmp/build/mobile/dist/* ./public/mobile/; fi
RUN if [ -d "/tmp/build/games/dist" ]; then cp -r /tmp/build/games/dist/* ./public/games/; fi

RUN rm -rf /tmp/build

ENV NODE_ENV=production
ENV PORT=8080
ENV API_PREFIX=/api

EXPOSE 8080

CMD ["bun", "src/index.ts"]
