# syntax=docker/dockerfile:1.7

FROM --platform=$BUILDPLATFORM golang:1.25-bookworm AS base

ARG TARGETOS
ARG TARGETARCH

WORKDIR /src

RUN apt-get update && apt-get install -y --no-install-recommends \
    git ca-certificates && rm -rf /var/lib/apt/lists/*

COPY go.mod ./
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download

COPY . .

FROM base AS builder
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} \
    go build -p "$(nproc)" -trimpath -ldflags="-s -w" -o /out/api ./cmd/api

FROM base AS webbuild
RUN apt-get update && apt-get install -y --no-install-recommends unzip curl && rm -rf /var/lib/apt/lists/* \
    && curl -fsSL https://bun.sh/install | bash \
    && mv /root/.bun/bin/bun /usr/local/bin/ && rm -rf /root/.bun
WORKDIR /src/libs/geo-api-client
RUN bun install && bun run build

FROM base AS dev
ENV ADDR=:8122
EXPOSE 8122
CMD ["go", "run", "./cmd/api"]

FROM base AS test
USER root
RUN apt-get update && apt-get install -y --no-install-recommends unzip curl && rm -rf /var/lib/apt/lists/* \
    && curl -fsSL https://bun.sh/install | bash \
    && mv /root/.bun/bin/bun /usr/local/bin/ && rm -rf /root/.bun
WORKDIR /src
CMD ["sh", "-c", "go test ./... && cd libs/geo-api-client && bun install && bun test"]

FROM gcr.io/distroless/static-debian12:nonroot AS runtime

WORKDIR /app
COPY --from=builder /out/api /app/api
COPY --from=builder /src/web /app/web
COPY --from=webbuild /src/libs /app/libs

ENV ADDR=:8122
EXPOSE 8122

ENTRYPOINT ["/app/api"]
