# syntax=docker/dockerfile:1
# Shared Dockerfile for all Go services
# Usage: docker build --build-arg SERVICE=gateway -t gateway .

ARG SERVICE=gateway

# Build stage
FROM golang:1.25-alpine AS builder

ARG SERVICE

RUN apk add --no-cache git ca-certificates tzdata

WORKDIR /app

# Copy module files for dependency caching (don't use go.work in container)
COPY pkg/go.mod pkg/go.sum ./pkg/
COPY pkg/can-go/go.mod pkg/can-go/go.sum ./pkg/can-go/
COPY services/${SERVICE}/go.mod services/${SERVICE}/go.sum ./services/${SERVICE}/

# Download dependencies (cached layer)
WORKDIR /app/services/${SERVICE}
RUN --mount=type=cache,target=/go/pkg/mod \
    go mod download -x

# Copy source
WORKDIR /app
COPY pkg/ ./pkg/
COPY services/${SERVICE}/ ./services/${SERVICE}/

# Build static binary
WORKDIR /app/services/${SERVICE}
RUN --mount=type=cache,target=/go/pkg/mod \
    --mount=type=cache,target=/root/.cache/go-build \
    CGO_ENABLED=0 GOOS=linux \
    go build -ldflags="-s -w" -trimpath -o /app-binary .

# Runtime stage - distroless for minimal attack surface
FROM gcr.io/distroless/static-debian12:nonroot

ARG SERVICE

COPY --from=builder /app-binary /app
COPY --from=builder /app/pkg/logger/log_config /log_config
COPY --from=builder /usr/share/zoneinfo /usr/share/zoneinfo

# Copy docs if they exist (optional)
COPY --from=builder /app/services/${SERVICE}/docs* /docs/

ENV LOG_CONFIG=/log_config
ENV TZ=UTC

ENTRYPOINT ["/app"]
