# ==================================================
# OCDP Backend - Dockerfile
# 构建 backend 服务（连接 PostgreSQL）
# ==================================================
FROM golang:1.24-alpine AS builder

ARG GOPROXY=https://goproxy.cn,direct
ARG GOSUMDB=sum.golang.google.cn
ENV GOPROXY=${GOPROXY}
ENV GOSUMDB=${GOSUMDB}

RUN apk add --no-cache git make

WORKDIR /build

COPY go.mod go.sum ./
RUN sh -c 'for i in 1 2 3; do go mod download && exit 0; echo "go mod download failed, retrying ($i/3)" >&2; sleep 5; done; go mod download'

COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-w -s" -o ocdp-backend cmd/api/main.go

# ==================================================
# Runtime
# ==================================================
FROM alpine:latest

RUN apk --no-cache add ca-certificates curl

RUN addgroup -g 1000 ocdp && \
    adduser -D -u 1000 -G ocdp ocdp

WORKDIR /app

COPY --from=builder /build/ocdp-backend .
COPY --from=builder /build/config ./config

RUN chown -R ocdp:ocdp /app

USER ocdp

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

CMD ["./ocdp-backend"]
