FROM golang:1.24.1 AS gobuild
WORKDIR /usr/src/app

# Download Go modules
COPY backend/go.mod backend/go.sum .
RUN go mod download

# Copy the source code. Note the slash at the end, as explained in
# https://docs.docker.com/engine/reference/builder/#copy
COPY backend/*.go ./

# Build
RUN CGO_ENABLED=0 GOOS=linux go build -o custom_pocketbase

FROM oven/bun:latest AS base
WORKDIR /usr/src/app

# install dependencies into temp directory
# this will cache them and speed up future builds
FROM base AS install
RUN mkdir -p /temp/dev
COPY frontend/package.json frontend/bun.lock /temp/dev/
RUN cd /temp/dev && bun install --frozen-lockfile

# copy node_modules from temp directory
# then copy all (non-ignored) project files into the image
FROM base AS prerelease
COPY --from=install /temp/dev/node_modules node_modules
COPY frontend .

# [optional] tests & build
ENV NODE_ENV=production
RUN bun run build

# copy production dependencies and source code into final image
FROM oven/bun:alpine AS release
WORKDIR /usr/src/app

ENV GO_ENV=production
COPY start_server.sh .
COPY --from=prerelease /usr/src/app/build .
COPY --from=gobuild /usr/src/app/custom_pocketbase .
COPY backend/pb_migrations ./pb_migrations

# run the app
EXPOSE 8090
ENTRYPOINT [ "./start_server.sh" ]
