# syntax=docker/dockerfile:1
# Agent Engine — web (Next.js dashboard, internal + public APIs, widget host)
# Build context: apps/web

# --- deps -------------------------------------------------------------------
# Full install (dev deps included) — next build needs them.
FROM node:20-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

# --- build ------------------------------------------------------------------
# NEXT_PUBLIC_* are inlined into the client bundle at build time (see
# src/lib/supabase/client.ts), so they must be present here, not just at
# runtime. Both are publishable values — nothing secret is baked in.
FROM node:20-slim AS build
WORKDIR /app
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \
    NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=$NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY \
    NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

# --- prod deps --------------------------------------------------------------
FROM node:20-slim AS prod-deps
WORKDIR /app
COPY package.json package-lock.json ./
# typescript is a devDependency, but `next start` transpiles next.config.ts on
# boot and fails without it — so it is needed at runtime too. --no-save keeps
# package.json and the lockfile untouched.
RUN npm ci --omit=dev && npm install --no-save typescript

# --- runner -----------------------------------------------------------------
FROM node:20-slim AS runner
WORKDIR /app
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3000 \
    HOSTNAME=0.0.0.0 \
    PLAYWRIGHT_BROWSERS_PATH=/ms-playwright

COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build     /app/.next        ./.next
COPY package.json next.config.ts ./
COPY public ./public

# Chromium for the Connected Agents live-website preview snapshot. Without it
# that one feature degrades to an error at runtime (the import is dynamic and
# handled) — everything else works. Drop this layer if the image size matters
# more than the preview.
RUN npx --yes playwright install --with-deps chromium \
 && chmod -R a+rX /ms-playwright \
 && rm -rf /var/lib/apt/lists/*

USER node
EXPOSE 3000

HEALTHCHECK --interval=15s --timeout=5s --start-period=40s --retries=5 \
  CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/').then(r=>process.exit(r.status<500?0:1)).catch(()=>process.exit(1))"

CMD ["node_modules/.bin/next", "start"]
