# Build stage
FROM node:20-alpine AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY prisma ./prisma/
RUN DATABASE_URL="file:/app/data/snapshot.db" npx prisma generate

COPY . .
RUN npm run build

# Production stage
FROM node:20-slim AS production

WORKDIR /app

# 安装系统工具 + PostgreSQL 16 客户端 (匹配目标数据库版本)
RUN apt-get update && apt-get install -y --no-install-recommends \
    openssl curl ca-certificates gnupg lsb-release \
    && echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
       > /etc/apt/sources.list.d/pgdg.list \
    && curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /etc/apt/trusted.gpg.d/pgdg.gpg \
    && apt-get update && apt-get install -y --no-install-recommends \
       postgresql-client-16 gzip \
    && apt-get purge -y gnupg lsb-release && apt-get autoremove -y \
    && rm -rf /var/lib/apt/lists/*

# 安装 MinIO 客户端 (mc)
RUN curl -fsSL https://dl.min.io/client/mc/release/linux-amd64/mc -o /usr/local/bin/mc \
    && chmod +x /usr/local/bin/mc

COPY package*.json ./
RUN npm ci --only=production

COPY prisma ./prisma/
RUN DATABASE_URL="file:/app/data/snapshot.db" npx prisma generate

COPY --from=builder /app/dist ./dist

# 创建数据目录
RUN mkdir -p /app/data/snapshots

# 启动脚本: SQLite 用 db push 而非 migrate deploy
RUN echo '#!/bin/sh\n\
set -e\n\
echo "Initializing SQLite database..."\n\
npx prisma db push --skip-generate\n\
echo "Starting snapshot service..."\n\
exec node dist/main.js\n' > /app/start.sh && chmod +x /app/start.sh

EXPOSE 3099

HEALTHCHECK --interval=30s --timeout=3s --start-period=30s --retries=3 \
  CMD curl -f http://localhost:${APP_PORT:-3099}/api/v1/health || exit 1

CMD ["/app/start.sh"]
