# Use the official Bun image
FROM oven/bun:1 AS base

# Set the working directory inside the container
WORKDIR /app

# ---
FROM base AS prepare

RUN bun add -g turbo@^2
COPY . .
RUN turbo prune web --docker


# ---
FROM base AS builder

# First install the dependencies (as they change less often)
COPY --from=prepare /app/out/json/ .
RUN bun install
# Build the project
COPY --from=prepare /app/out/full/ .

ARG PUBLIC_CONVEX_URL
ENV PUBLIC_CONVEX_URL=$PUBLIC_CONVEX_URL

ARG PUBLIC_CONVEX_SITE_URL
ENV PUBLIC_CONVEX_SITE_URL=$PUBLIC_CONVEX_SITE_URL

RUN bunx turbo build

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

# Set working directory to match builder structure
WORKDIR /app

# Create non-root user
RUN addgroup --system --gid 1001 sveltekit
RUN adduser --system --uid 1001 sveltekit

# Copy root node_modules (contains hoisted dependencies)
COPY --from=builder --chown=sveltekit:sveltekit /app/node_modules ./node_modules

# Copy built application and workspace files
COPY --from=builder --chown=sveltekit:sveltekit /app/apps/web/build ./apps/web/build
COPY --from=builder --chown=sveltekit:sveltekit /app/apps/web/package.json ./apps/web/package.json
# Copy workspace node_modules (contains symlinks to root node_modules)
COPY --from=builder --chown=sveltekit:sveltekit /app/apps/web/node_modules ./apps/web/node_modules

# Copy any additional files needed for runtime
COPY --from=builder --chown=sveltekit:sveltekit /app/apps/web/static ./apps/web/static

# Switch to non-root user
USER sveltekit

# Set working directory to the app
WORKDIR /app/apps/web

# Expose the port that the app runs on
EXPOSE 5173

# Set environment variables
ENV NODE_ENV=production
ENV PORT=5173

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
	CMD bun --version || exit 1

# Start the application
CMD ["bun", "./build/index.js"]
