FROM golang:1.27.1-alpine AS builder

WORKDIR /app

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

COPY cmd/api/ ./cmd/api/
COPY cmd/attachment-cleanup/ ./cmd/attachment-cleanup/
COPY internal/ ./internal/

RUN CGO_ENABLED=0 GOOS=linux go build -o /app/server ./cmd/api
RUN CGO_ENABLED=0 GOOS=linux go build -o /app/attachment-cleanup ./cmd/attachment-cleanup


FROM alpine:3.22 AS runtime

RUN addgroup -S app && adduser -S app -G app

WORKDIR /app

USER app

FROM runtime AS cleanup

COPY --from=builder /app/attachment-cleanup ./attachment-cleanup
CMD ["./attachment-cleanup"]

FROM runtime AS api

COPY --from=builder /app/server ./server
EXPOSE 8080

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

CMD ["./server"]
