# syntax=docker/dockerfile:1.7
# ── Stage 1: Dependencies ─────────────────────────────────────────────
FROM golang:1.22-alpine AS deps
WORKDIR /build
COPY go.mod go.sum ./
RUN go mod download

# ── Stage 2: Test ─────────────────────────────────────────────────────
FROM deps AS test
COPY . .
RUN go test ./... -race -count=1

# ── Stage 3: Build ────────────────────────────────────────────────────
FROM deps AS builder
ARG VERSION=dev
ARG COMMIT=none
ARG BUILD_DATE=unknown

COPY . .

# CGO_ENABLED=0 produces a statically linked binary that runs in FROM scratch
RUN CGO_ENABLED=0 GOOS=linux go build \
  -ldflags="-s -w \
    -X main.Version=${VERSION} \
    -X main.Commit=${COMMIT} \
    -X main.BuildDate=${BUILD_DATE}" \
  -o /bin/taskapi \
  ./cmd/taskapi

# ── Stage 4: Certs (needed for outbound HTTPS) ────────────────────────
FROM alpine:3.19 AS certs
RUN apk --no-cache add ca-certificates

# ── Stage 5: Runtime (FROM scratch — zero OS footprint) ──────────────
FROM scratch

# Copy the TLS certificate bundle
COPY --from=certs /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/

# Copy the binary, owned by the non-root UID 65534 (nobody)
COPY --from=builder --chown=65534:65534 /bin/taskapi /taskapi

# OCI image labels for provenance and registry display
ARG VERSION=dev
ARG COMMIT=none
ARG BUILD_DATE=unknown
LABEL org.opencontainers.image.title="taskapi" \
      org.opencontainers.image.description="Go for Cloud & DevOps — Task API" \
      org.opencontainers.image.version="${VERSION}" \
      org.opencontainers.image.revision="${COMMIT}" \
      org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.source="https://github.com/yourorg/taskapi"

USER 65534:65534

# Health check — invokes the binary's built-in health check mode
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD ["/taskapi", "-health-check"]

ENTRYPOINT ["/taskapi"]
