FROM rust:1.90-bookworm AS chef
WORKDIR /app
RUN cargo install cargo-chef

FROM chef AS planner
WORKDIR /app/services/data-persistence-service
# 仅复制必要的 Cargo 清单，避免大体积上下文
COPY services/common-contracts/Cargo.toml /app/services/common-contracts/Cargo.toml
COPY services/data-persistence-service/Cargo.toml /app/services/data-persistence-service/Cargo.toml
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS builder
ENV SQLX_OFFLINE=true
WORKDIR /app/services/data-persistence-service
COPY --from=planner /app/services/data-persistence-service/recipe.json /app/services/data-persistence-service/recipe.json
# 为了支持 path 依赖，先拷贝依赖源码再 cook
COPY services/common-contracts /app/services/common-contracts
RUN cargo chef cook --release --recipe-path /app/services/data-persistence-service/recipe.json
# 复制服务源码用于实际构建
COPY services/common-contracts /app/services/common-contracts
COPY services/data-persistence-service /app/services/data-persistence-service
RUN cargo build --release --bin data-persistence-service-server

FROM debian:bookworm-slim AS runtime
WORKDIR /app
RUN groupadd --system --gid 1001 appuser && \
    useradd --system --uid 1001 --gid 1001 appuser
USER appuser
COPY --from=builder /app/services/data-persistence-service/target/release/data-persistence-service-server /usr/local/bin/data-persistence-service-server
COPY services/data-persistence-service/migrations ./migrations
ENV HOST=0.0.0.0
ENV PORT=3000
EXPOSE 3000
ENTRYPOINT ["/usr/local/bin/data-persistence-service-server"]
