# Stage 1: Build SvelteKit static frontend
FROM oven/bun:alpine AS frontend-builder
WORKDIR /app
COPY package.json ./
RUN bun install
COPY . .
RUN bun run build

# Stage 2: Build Golang server
FROM golang:1.23-alpine AS backend-builder
# Enable CGO for SQLite3 compiling
RUN apk add --no-cache gcc musl-dev
WORKDIR /app
COPY server/go.mod ./
# Copy go.sum if it exists
COPY server/go.su[m] ./
RUN go mod download
COPY server/ ./
RUN CGO_ENABLED=1 GOOS=linux go build -o sim-link-server .

# Stage 3: Final lightweight runtime image
FROM alpine:latest
WORKDIR /app

# Install sqlite-libs, tzdata for go-sqlite3 runtime, and ffmpeg for faststart .avi/.mp4 transcoding
RUN apk add --no-cache sqlite-libs tzdata ffmpeg

# Copy built frontend from Stage 1
COPY --from=frontend-builder /app/build ./build

# Copy built Golang binary to system bin so we can run it from any directory
COPY --from=backend-builder /app/sim-link-server /usr/local/bin/sim-link-server

# Change to a server sub-directory so relative paths like "../build"
# and "../results" still resolve properly just as they did in dev.
WORKDIR /app/server

EXPOSE 8080

CMD ["sim-link-server"]
