# 构建阶段
FROM golang:alpine as builder

# 设置工作目录和构建环境
WORKDIR /build
ENV CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64

# 复制并下载依赖
COPY go.mod go.sum ./
RUN go mod download

# 复制源代码并构建
COPY . .
RUN go build -ldflags="-s -w" -o app
# 给bun添加一下可执行权限
RUN chmod a+x ./docker/bin/bun

# 运行阶段
FROM alpine:latest

# 设置运行环境
ENV IS_DOCKER=true \
    TZ=Asia/Shanghai

# 安装必要的运行时依赖
RUN apk add --no-cache ca-certificates tzdata curl uv \
    && mkdir -p /app/data /app/logs \
    && adduser -D -H -h /app appuser \
    && chown -R appuser:appuser /app

# 设置工作目录
WORKDIR /app

# 复制bun到容器内
COPY --from=builder /build/docker/bin/bun /usr/local/bin/bun

# 从构建阶段复制二进制文件
COPY --from=builder /build/app ./
COPY --from=builder /build/configs ./configs
COPY --from=builder /build/internal/view ./internal/view
COPY --from=builder /build/public ./public

# 设置所有者
RUN chmod +x ./app && chown -R appuser:appuser /app

# 切换到非root用户
USER appuser

# 声明端口
EXPOSE 9000

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:9000/health || exit 1

# 定义卷
VOLUME ["/app/data", "/app/logs"]

# 添加元数据标签
LABEL maintainer="lxh@cxh.cn" \
      description="Wechat Robot Management System" \
      version="1.0.0"

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