# ========== 构建阶段 ==========
FROM golang:1.23-alpine AS builder

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

WORKDIR /app

# 复制 go.mod 并下载依赖（利用 Docker 缓存层）
COPY go.mod ./
RUN go mod download

# 复制源代码
COPY . .

# 编译 (静态链接，适配 Alpine)
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /iot-debug-service ./cmd/main.go

# ========== 运行阶段 ==========
FROM alpine:3.20

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

WORKDIR /app

# 从构建阶段复制二进制文件
COPY --from=builder /iot-debug-service .

# 非 root 用户
RUN adduser -D -H cyrene
USER cyrene

EXPOSE 8083

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8083/api/v1/health || exit 1

ENTRYPOINT ["./iot-debug-service"]
