# Build context: bytelyst-devops-tools/dashboard/ (monorepo root)
#
# Uses pnpm (matches `packageManager` field) and the workspace
# `pnpm-lock.yaml`. See backend/Dockerfile for the full background on
# why the previous `npm ci` based build was broken (pnpm-store symlinks
# leaking into the npm lockfile).

# --- Stage 1: Build ---
FROM node:20-alpine AS builder

ENV BYTELYST_PACKAGE_SOURCE=gitea
RUN corepack enable && corepack prepare pnpm@10.6.5 --activate

WORKDIR /app

ARG GITEA_NPM_HOST=host.docker.internal
ARG GITEA_NPM_OWNER=learning_ai_user

COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .pnpmfile.cjs ./
COPY web/package.json ./web/

RUN printf '@bytelyst:registry=http://%s:3300/api/packages/%s/npm/\n' "$GITEA_NPM_HOST" "$GITEA_NPM_OWNER" > .npmrc
RUN pnpm install --frozen-lockfile --filter "@bytelyst/devops-web..." --ignore-scripts

COPY web/tsconfig.json ./web/
COPY web/next-env.d.ts ./web/
COPY web/next.config.js ./web/
COPY web/tailwind.config.ts ./web/
COPY web/postcss.config.js ./web/
COPY web/src/ ./web/src/
COPY web/public/ ./web/public/

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

# 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=devops-web:latest

ENV NEXT_PUBLIC_PRODUCT_ID=${NEXT_PUBLIC_PRODUCT_ID} \
    NEXT_PUBLIC_PLATFORM_URL=${NEXT_PUBLIC_PLATFORM_URL} \
    NEXT_PUBLIC_DEVOPS_API_URL=${NEXT_PUBLIC_DEVOPS_API_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}

WORKDIR /app/web
RUN pnpm run build

# Carve out a production-only deploy bundle.
WORKDIR /app
RUN pnpm --filter "@bytelyst/devops-web" deploy --prod --legacy /deploy

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

WORKDIR /app/web

COPY --from=builder /deploy/package.json ./package.json
COPY --from=builder /deploy/node_modules ./node_modules
COPY --from=builder /app/web/.next ./.next
COPY --from=builder /app/web/public ./public

ENV NODE_ENV=production
ENV PORT=3000

EXPOSE 3000

CMD ["npm", "run", "start"]
