# Build stage
FROM oven/bun:1 AS build
WORKDIR /app

# Copy package files
COPY package.json bun.lock* ./

# Copy local SDK dependency (package.json references file:../encryptid-sdk)
COPY --from=encryptid-sdk . /encryptid-sdk/

RUN bun install

# Copy source
COPY . .

# Build frontend (skip tsc in Docker — type checking is done in CI/local dev)
RUN bunx vite build

# Typst binary stage — download once, reuse in production
FROM debian:bookworm-slim AS typst
RUN apt-get update && apt-get install -y --no-install-recommends curl xz-utils ca-certificates \
    && curl -fsSL https://github.com/typst/typst/releases/download/v0.13.1/typst-x86_64-unknown-linux-musl.tar.xz \
       -o /tmp/typst.tar.xz \
    && tar xf /tmp/typst.tar.xz -C /tmp \
    && mv /tmp/typst-x86_64-unknown-linux-musl/typst /usr/local/bin/typst \
    && rm -rf /tmp/typst* \
    && chmod +x /usr/local/bin/typst

# Production stage
FROM oven/bun:1-slim AS production
WORKDIR /app

# Install Typst binary (for rPubs PDF generation)
COPY --from=typst /usr/local/bin/typst /usr/local/bin/typst

# Copy built assets and server
COPY --from=build /app/dist ./dist
COPY --from=build /app/server ./server
COPY --from=build /app/lib ./lib
COPY --from=build /app/shared ./shared
COPY --from=build /app/modules ./modules
COPY --from=build /app/src ./src
COPY --from=build /app/package.json .
COPY --from=build /encryptid-sdk /encryptid-sdk

# Install production dependencies only
RUN bun install --production

# Create data directories
RUN mkdir -p /data/communities /data/books /data/swag-artifacts /data/files /data/splats

# Copy entrypoint for Infisical secret injection
COPY entrypoint.sh /app/entrypoint.sh
COPY scripts/ /app/scripts/
RUN chmod +x /app/entrypoint.sh /app/scripts/*.sh

# Set environment
ENV NODE_ENV=production
ENV STORAGE_DIR=/data/communities
ENV BOOKS_DIR=/data/books
ENV SWAG_ARTIFACTS_DIR=/data/swag-artifacts
ENV FILES_DIR=/data/files
ENV SPLATS_DIR=/data/splats
ENV PORT=3000

# Data volumes for persistence
VOLUME /data/communities
VOLUME /data/books
VOLUME /data/swag-artifacts
VOLUME /data/files
VOLUME /data/splats

EXPOSE 3000

ENTRYPOINT ["/app/entrypoint.sh"]
CMD ["bun", "run", "server/index.ts"]
