# Build context: learning_ai_common_plat/ (monorepo root)
# --- Stage 1: Build ---
FROM node:20-alpine AS builder

RUN corepack enable && corepack prepare pnpm@10.6.5 --activate

WORKDIR /app

# Gitea npm registry for @bytelyst/* packages
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY packages/ packages/
COPY dashboards/admin-web/package.json dashboards/admin-web/

RUN --mount=type=secret,id=gitea_npm_token \
  TOKEN=$(cat /run/secrets/gitea_npm_token) && \
  printf '@bytelyst:registry=http://localhost:3300/api/packages/learning_ai_user/npm/\n//localhost:3300/api/packages/learning_ai_user/npm/:_authToken=%s\n' "$TOKEN" > .npmrc && \
  pnpm install --ignore-scripts --legacy-peer-deps

COPY dashboards/admin-web/ dashboards/admin-web/

# Build-time env vars (baked into the static bundle)
ARG NEXT_PUBLIC_PRODUCT_ID=admin
ARG NEXT_PUBLIC_PLATFORM_URL=https://api.bytelyst.com/platform/api

# Build metadata for @bytelyst/devops (web bundle)
ARG BYTELYST_COMMIT_SHA=unknown
ARG BYTELYST_COMMIT_SHA_FULL=unknown
ARG BYTELYST_BRANCH=unknown
ARG BYTELYST_BUILT_AT=unknown
ARG BYTELYST_COMMIT_AUTHOR=unknown
ARG BYTELYST_COMMIT_MESSAGE=unknown
ARG BYTELYST_DOCKER_IMAGE=admin-web:latest

ENV NEXT_PUBLIC_PRODUCT_ID=${NEXT_PUBLIC_PRODUCT_ID} \
    NEXT_PUBLIC_PLATFORM_URL=${NEXT_PUBLIC_PLATFORM_URL} \
    NEXT_PUBLIC_BYTELYST_COMMIT_SHA=${BYTELYST_COMMIT_SHA} \
    NEXT_PUBLIC_BYTELYST_COMMIT_SHA_FULL=${BYTELYST_COMMIT_SHA_FULL} \
    NEXT_PUBLIC_BYTELYST_BRANCH=${BYTELYST_BRANCH} \
    NEXT_PUBLIC_BYTELYST_BUILT_AT=${BYTELYST_BUILT_AT} \
    NEXT_PUBLIC_BYTELYST_COMMIT_AUTHOR=${BYTELYST_COMMIT_AUTHOR} \
    NEXT_PUBLIC_BYTELYST_COMMIT_MESSAGE=${BYTELYST_COMMIT_MESSAGE} \
    NEXT_PUBLIC_BYTELYST_DOCKER_IMAGE=${BYTELYST_DOCKER_IMAGE} \
    NEXT_TELEMETRY_DISABLED=1

RUN NODE_OPTIONS=--max-old-space-size=8192 pnpm -r --filter @bytelyst/admin-web... build
RUN pnpm --filter @bytelyst/admin-web deploy --legacy --ignore-scripts /app/deploy

# --- Stage 2: Serve ---
FROM node:20-alpine AS runner

WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3001
ENV HOSTNAME=0.0.0.0

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

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

USER nextjs

EXPOSE 3001

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