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

WORKDIR /build

# 安装构建依赖
RUN apk add --no-cache git ca-certificates tzdata

# 复制 Go 模块文件
COPY go.mod go.sum ./
RUN go mod download

# 复制源代码
COPY . .

# 编译应用
ARG GIN_MODE=release
ENV GIN_MODE=${GIN_MODE}
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-w -s" -o server ./cmd/server

# 运行阶段
FROM alpine:3.19

WORKDIR /app

# 安装运行时依赖
RUN apk add --no-cache ca-certificates tzdata

# 创建非 root 用户
RUN addgroup -g 1000 appgroup && adduser -u 1000 -G appgroup -s /bin/sh -D appuser

# 从构建阶段复制二进制文件
COPY --from=builder /build/server .
COPY --from=builder /build/configs ./configs
COPY --from=builder /build/data ./data

# 创建日志目录并设置权限
RUN mkdir -p /app/logs && chown -R appuser:appgroup /app

# 设置时区
ENV TZ=Asia/Shanghai
ENV GIN_MODE=release

# 暴露端口
EXPOSE 8080

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

# 切换到非 root 用户
USER appuser

# 启动命令
CMD ["./server"]
