# Next.js 应用 Dockerfile
FROM node:18-alpine AS base

# 安装依赖阶段
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app

# 复制依赖文件
COPY package.json package-lock.json* pnpm-lock.yaml* ./

# 优先使用pnpm，如果没有则使用npm
RUN if [ -f pnpm-lock.yaml ]; then \
        corepack enable && corepack prepare pnpm@latest --activate && \
        pnpm install --frozen-lockfile; \
    else \
        npm ci --legacy-peer-deps || npm install --legacy-peer-deps; \
    fi

# 构建阶段
FROM base AS builder
WORKDIR /app

# 启用corepack（如果需要pnpm）
RUN corepack enable || true

COPY --from=deps /app/node_modules ./node_modules
COPY . .

# 设置环境变量
ENV NEXT_TELEMETRY_DISABLED 1

# 构建应用 - 优先使用pnpm
RUN if [ -f pnpm-lock.yaml ]; then \
        corepack prepare pnpm@latest --activate && pnpm build; \
    else \
        npm run build; \
    fi

# 生产运行阶段
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# 复制必要文件
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

CMD ["node", "server.js"]
