# syntax=docker/dockerfile:1

# Stage 1: Build static Go binary
FROM golang:1.24-alpine AS builder
WORKDIR /src

ENV GOPROXY=https://goproxy.io,direct
ENV GOSUMDB=off

# Cache dependencies first
COPY go.mod go.sum ./
RUN go mod download

# Copy application source and migrations
COPY cmd/ ./cmd/
COPY internal/ ./internal/
COPY migrations/ ./migrations/

# Build stripped static binary
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-s -w" -o /out/messenger ./cmd/server

# Stage 2: Minimal non-root runtime image
FROM alpine:3.21
RUN addgroup -g 10001 -S appgroup && \
    adduser -u 10001 -S appuser -G appgroup

WORKDIR /app
COPY --from=builder /out/messenger /app/messenger
COPY --from=builder /src/migrations /app/migrations
RUN chown -R appuser:appgroup /app

USER 10001:10001
EXPOSE 8080

HEALTHCHECK --interval=2s --timeout=2s --start-period=2s --retries=10 \
  CMD wget -q -O /dev/null http://127.0.0.1:8080/health/ready || exit 1

ENTRYPOINT ["/app/messenger"]
