# Coolify production image: Next.js standalone app with Blender for Draco compression.

# --- Stage 1: Dependencies ---------------------------------------------------
FROM node:20-slim AS deps

WORKDIR /app

COPY package.json package-lock.json* .npmrc ./
RUN npm ci --ignore-scripts --no-audit --no-fund

# --- Stage 2: Build ----------------------------------------------------------
FROM node:20-slim AS builder

WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY . .

ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production

RUN npm run build

# --- Stage 3: Production -----------------------------------------------------
FROM node:20-slim AS runner

ARG KTX_SOFTWARE_VERSION=4.4.2

LABEL maintainer="La Fabrik Durable"
LABEL description="Secure GLTF upload interface with Draco/KTX2 compression and Git push"

# Blender is required for server-side Draco GLB export.
# KTX-Software provides toktx for optional KTX2 texture delivery.
RUN apt-get update && apt-get install -y --no-install-recommends \
    bzip2 \
    blender \
    ca-certificates \
    tini \
    curl \
    && curl -fsSL \
      "https://github.com/KhronosGroup/KTX-Software/releases/download/v${KTX_SOFTWARE_VERSION}/KTX-Software-${KTX_SOFTWARE_VERSION}-Linux-x86_64.tar.bz2" \
      -o /tmp/ktx-software.tar.bz2 \
    && mkdir -p /opt/ktx-software \
    && tar -xjf /tmp/ktx-software.tar.bz2 -C /opt/ktx-software --strip-components=1 \
    && ln -s /opt/ktx-software/bin/toktx /usr/local/bin/toktx \
    && rm -rf /tmp/ktx-software.tar.bz2 /var/lib/apt/lists/*

WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public

COPY --from=builder /app/scripts ./scripts

RUN mkdir -p /tmp/assets

COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh

EXPOSE 3000

ENTRYPOINT ["/usr/bin/tini", "--", "/docker-entrypoint.sh"]
CMD ["node", "server.js"]
