# Stage 1: Install dependencies
FROM docker.io/oven/bun:1.3.3-alpine AS deps
WORKDIR /app
COPY package.json bun.lock ./

RUN apk add --no-cache python3 make g++

RUN bun i --frozen-lockfile

# Stage 2: Build the SvelteKit application
FROM docker.io/oven/bun:1.3.3-alpine AS builder
WORKDIR /app

ARG DATABASE_URL
ENV DATABASE_URL=$DATABASE_URL

COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Build the application with the Node.js adapter
RUN bun run build

# Prune dev dependencies after build
# We will have to wait for bun support big sad
# RUN bun prune --omit=dev

# Stage 3: Production runtime
FROM docker.io/oven/bun:1.3.3-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production

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

# Copy the built application
COPY --from=builder --chown=sveltekit:sveltekit /app/build ./build

# Copy production dependencies
COPY --from=builder --chown=sveltekit:sveltekit /app/node_modules ./node_modules

# Copy package.json for module resolution
COPY --chown=sveltekit:sveltekit package.json .

USER sveltekit

EXPOSE 3000
ENV PORT=3000
ENV HOST=0.0.0.0

# Start the SvelteKit server
CMD ["bun", "--bun", "build/index.js"]
