# ─── Build Stage ──────────────────────────────────────────────────────────────
FROM golang:1.21-alpine AS builder

WORKDIR /build

# Allow go to fetch modules even without a pre-generated go.sum
ENV GOFLAGS=-mod=mod
ENV GONOSUMDB=*

COPY go.mod ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
    go build -ldflags="-w -s" -o sproutworkcollect-backend .

# ─── Runtime Stage ────────────────────────────────────────────────────────────
FROM alpine:3.19

RUN apk add --no-cache ca-certificates tzdata wget && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

WORKDIR /app

COPY --from=builder /build/sproutworkcollect-backend .

# Default data directories; override by mounting volumes at runtime
RUN mkdir -p /data/works /data/config

EXPOSE 5000

ENV SPROUTWORKCOLLECT_DATA_DIR=/data
ENV PORT=5000

HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
    CMD wget -qO- http://localhost:5000/api/settings || exit 1

CMD ["./sproutworkcollect-backend"]
