# Build Stage
FROM golang:1.24-alpine AS builder

# 1. 设置 Alpine 国内镜像源 (阿里云)
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories

# 2. 安装必要构建工具 (如 git, 因为 go mod 可能需要)
RUN apk add --no-cache git postgresql-client

WORKDIR /app

# Copy dependency files
COPY go.mod ./
COPY go.sum ./ 

# 3. 设置 Go 国内代理
RUN go env -w GOPROXY=https://goproxy.cn,direct

# Download dependencies first to cache them
RUN go mod download

# Copy all source code
COPY . .

# Run tidy to ensure everything is consistent
RUN go mod tidy

# Build the binary
RUN CGO_ENABLED=0 GOOS=linux go build -o ems-server .

# Runtime Stage
FROM alpine:latest

# 4. 运行时镜像也设置国内源 (方便排查问题安装工具)
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories
# 设置时区为上海，并安装 postgresql-client
RUN apk add --no-cache tzdata postgresql-client && \
    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone

WORKDIR /app

COPY --from=builder /app/ems-server .
COPY db/migrations /app/migrations

EXPOSE 8080

CMD ["./ems-server"]

