FROM node:20-alpine AS base
WORKDIR /app
 
# 阶段1: 安装所有依赖（包括 devDependencies，因为构建需要）
FROM base AS deps
COPY package*.json ./
RUN npm ci
 
# 阶段2: 构建应用
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npx prisma generate
ENV DATABASE_URL="file:./dev.db"
RUN npx prisma db push
RUN npm run build
 
# 阶段3: 生产运行环境
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
 
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 nextjs
 
# 复制 standalone 构建输出
COPY --from=builder /app/.next/standalone ./
# 复制静态文件
COPY --from=builder /app/.next/static ./.next/static
# 复制 prisma schema (用于数据库迁移)
COPY --from=builder /app/prisma ./prisma
# 复制 public 静态文件
COPY --from=builder /app/public ./public
 
RUN mkdir -p /app/data && chown nextjs:nodejs /app/data
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]
