# Builds the web app as a Next.js standalone server. Build from the repo root:
#   docker build -f apps/web/Dockerfile --build-arg NEXT_PUBLIC_API_URL=https://api.example.com .

FROM node:22-bookworm-slim AS base
WORKDIR /app

FROM base AS prepare
RUN npm install -g turbo@2.11.7
COPY . .
RUN turbo prune @musicshare/web --docker

FROM base AS builder
COPY --from=prepare /app/out/json/ .
RUN npm ci
COPY --from=prepare /app/out/full/ .
# turbo prune only copies workspaces; the shared tsconfig they extend lives at the root
COPY --from=prepare /app/tsconfig.base.json ./tsconfig.base.json
# NEXT_PUBLIC_* values are inlined into the browser bundle at build time,
# so the API URL is a build argument, not a runtime setting.
ARG NEXT_PUBLIC_API_URL=http://localhost:4000
ARG NEXT_PUBLIC_DONATION_URL=
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL \
    NEXT_PUBLIC_DONATION_URL=$NEXT_PUBLIC_DONATION_URL \
    NEXT_TELEMETRY_DISABLED=1
RUN npx turbo run build --filter=@musicshare/web

FROM base AS runner
ENV NODE_ENV=production \
    NEXT_TELEMETRY_DISABLED=1 \
    PORT=3737 \
    HOSTNAME=0.0.0.0
COPY --from=builder --chown=node:node /app/apps/web/.next/standalone ./
COPY --from=builder --chown=node:node /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder --chown=node:node /app/apps/web/public ./apps/web/public
USER node
EXPOSE 3737
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:' + process.env.PORT).then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
CMD ["node", "apps/web/server.js"]
