# ResearchX frontend — production release image (ciagent release system)
# Multi-stage: deps -> build -> runtime. Next.js standalone output.
# Built ON the Docker host from the synced source (no local docker required).

# ---- deps ----
FROM node:22-alpine AS deps
RUN corepack enable
WORKDIR /app
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
RUN pnpm install --frozen-lockfile

# ---- build ----
FROM node:22-alpine AS build
RUN corepack enable
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1

# Hosted build profile (PLAN.md T-4.3, RESEARCH-v03.md section 10): Next.js
# inlines NEXT_PUBLIC_* at BUILD time, so the profile is ARG/ENV here --
# never runtime flags. live mode + EMPTY base ("" = same-origin through the
# front proxy's /api path route): a non-empty base would break the
# same-origin session cookie behind the TLS front.
ARG NEXT_PUBLIC_RESEARCHX_API_MODE=live
ARG NEXT_PUBLIC_API_BASE_URL=""
ENV NEXT_PUBLIC_RESEARCHX_API_MODE="${NEXT_PUBLIC_RESEARCHX_API_MODE}" \
    NEXT_PUBLIC_API_BASE_URL="${NEXT_PUBLIC_API_BASE_URL}"

# Build assert: the hosted profile is hardwired -- mode=live, empty base --
# or the build fails before a wrong image can be produced.
RUN [ "$NEXT_PUBLIC_RESEARCHX_API_MODE" = "live" ] \
    && [ -z "$NEXT_PUBLIC_API_BASE_URL" ] \
    || { echo "hosted build profile violated: mode=$NEXT_PUBLIC_RESEARCHX_API_MODE" >&2; exit 1; }

COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN pnpm build

# ---- runtime ----
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0
RUN addgroup -S researchx && adduser -S researchx -G researchx

# Standalone output: the server + minimal node_modules only.
COPY --from=build --chown=researchx:researchx /app/.next/standalone ./
COPY --from=build --chown=researchx:researchx /app/.next/static ./.next/static

USER researchx
EXPOSE 3000
CMD ["node", "server.js"]