FROM golang:1.26.2-alpine AS builder

WORKDIR /app

RUN apk add --no-cache git

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o /app/backend ./cmd/api

FROM alpine:3.22

WORKDIR /app

RUN apk add --no-cache ca-certificates \
  && addgroup -S bookra \
  && adduser -S -D -H -u 10001 -G bookra bookra

COPY --from=builder --chown=bookra:bookra /app/backend /app/
COPY --from=builder --chown=bookra:bookra /app/migrations /app/migrations

ENV PORT=8080
EXPOSE 8080

USER bookra

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget -qO- "http://127.0.0.1:${PORT:-8080}/healthz" >/dev/null || exit 1

CMD ["/app/backend"]
