FROM node:22-alpine AS base

# ============================================
# Stage 1: Install dependencies
# ============================================

FROM base AS builder

RUN apk add --no-cache gcompat
RUN corepack enable && corepack prepare pnpm@10.18.2 --activate
WORKDIR /app

# 复制 monorepo 根配置（catalog、lockfile 等）
COPY pnpm-workspace.yaml pnpm-lock.yaml package.json ./
# 复制 web 应用源码
COPY apps/web/package.json ./apps/web/package.json
COPY apps/web/next.config.ts ./apps/web/next.config.ts
COPY apps/web/tsconfig.json ./apps/web/tsconfig.json
COPY apps/web/postcss.config.mjs ./apps/web/postcss.config.mjs
COPY apps/web/app ./apps/web/app
COPY apps/web/components ./apps/web/components
COPY apps/web/lib ./apps/web/lib
COPY apps/web/types ./apps/web/types
COPY apps/web/public ./apps/web/public
COPY apps/web/proxy.ts ./apps/web/proxy.ts

RUN pnpm install --filter web

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

ARG NEXT_PUBLIC_CSMS_URL
ENV NEXT_PUBLIC_CSMS_URL=${NEXT_PUBLIC_CSMS_URL}

RUN pnpm --filter web run build

# ============================================
# Stage 2: Run Next.js application
# ============================================

FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
ENV NEXT_TELEMETRY_DISABLED=1

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

COPY --from=builder --chown=nextjs:nodejs /app/apps/web/public ./public

RUN mkdir .next && chown nextjs:nodejs .next

COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static

USER nextjs
EXPOSE 3000

CMD ["node", "apps/web/server.js"]
