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

WORKDIR /app

# 安装构建依赖
RUN apk add --no-cache gcc musl-dev

# 先复制 go.mod 和 go.sum 以利用 Docker 缓存
COPY go.mod go.sum ./
RUN go mod download

# 复制源码并构建
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o server ./cmd/server

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

WORKDIR /app

# 安装运行时依赖（ca-certificates 用于 HTTPS 请求，tzdata 用于时区）
RUN apk add --no-cache ca-certificates tzdata && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

# 从构建阶段复制二进制和配置文件
COPY --from=builder /app/server .
COPY --from=builder /app/config/ ./config/

# 健康检查
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:8080/health || exit 1

EXPOSE 8080

# 默认使用生产配置，可通过命令行参数覆盖
CMD ["./server", "config/config-prod.yaml"]
