# =============================================================================
# Single-service image: API + agent dashboard + customer widget in one process.
# Works as-is on Render, Railway, Fly.io and Koyeb.
# =============================================================================

# ---------- build ------------------------------------------------------------
FROM node:22-alpine AS build
WORKDIR /app

# Copy manifests first so the dependency layer caches across code changes.
COPY package.json package-lock.json ./
COPY server/package.json  server/
COPY web/package.json     web/
COPY widget/package.json  widget/
RUN npm ci

COPY . .

# Each frontend is served from a sub-path, so Vite must emit matching asset URLs.
# VITE_API_URL is deliberately unset: empty means same-origin, which is correct
# when one process serves both the bundle and the API.
RUN VITE_API_URL= VITE_BASE_PATH=/desk/ npm --workspace web    run build \
 && VITE_API_URL= VITE_BASE_PATH=/chat/ npm --workspace widget run build \
 && npm --workspace server run build

# ---------- runtime ----------------------------------------------------------
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production

# tini reaps zombies and forwards SIGTERM, so the graceful shutdown in
# src/index.ts actually runs when the platform stops the container.
RUN apk add --no-cache tini

COPY package.json package-lock.json ./
COPY server/package.json  server/
COPY web/package.json     web/
COPY widget/package.json  widget/
RUN npm ci --omit=dev && npm cache clean --force

# Compiled server (including db/schema.sql) plus both built frontends.
COPY --from=build /app/server/dist  ./server/dist
COPY --from=build /app/web/dist     ./web/dist
COPY --from=build /app/widget/dist  ./widget/dist

# Local-disk uploads. Mount a volume here, or switch STORAGE_DRIVER=s3 —
# a container filesystem does not survive a redeploy.
RUN mkdir -p /app/server/uploads && chown -R node:node /app/server/uploads
VOLUME ["/app/server/uploads"]

USER node
WORKDIR /app/server
EXPOSE 4000

# The platform's own health check can use this too.
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||4000)+'/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "dist/index.js"]
