# Stage 1: Compile libvips with HEIC support
FROM node:22-bullseye-slim AS libvips-builder

# Install build tools and dependencies for libvips and libheif
# These are Debian/Ubuntu package names
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    pkg-config \
    git \
    python3 \
    curl \
    meson \
    ninja-build \
    libglib2.0-dev \
    libexpat1-dev \
    libheif-dev \
    liblcms2-dev \
    libjpeg-dev \
    libpng-dev \
    libwebp-dev \
    libtiff-dev \
    libexif-dev \
    libgif-dev \
    # Dependencies for libheif codecs (libde265, x265)
    libde265-dev \
    libx265-dev \
    # Clean up apt cache
    && rm -rf /var/lib/apt/lists/*

# Define libvips version to build (check sharp's package.json for compatible versions)
# Sharp 0.34.x supports libvips 8.15+ (8.16.2 is latest stable at time of writing)
ARG LIBVIPS_VERSION=8.16.2

# Build libvips from source
WORKDIR /tmp
RUN git clone --branch v${LIBVIPS_VERSION} --depth 1 https://github.com/libvips/libvips.git \
    && cd libvips \
    && meson setup build --prefix=/usr --buildtype=release \
    && ninja -C build \
    && ninja -C build install \
    && ldconfig \
    && cd / \
    && rm -rf /tmp/libvips

# Stage 2: Build the Next.js app, linking sharp to the custom libvips
FROM node:22-bullseye-slim AS builder

WORKDIR /app

# Set environment variables for sharp to find libvips
ENV LD_LIBRARY_PATH=/usr/lib:$LD_LIBRARY_PATH
ENV PKG_CONFIG_PATH=/usr/lib/pkgconfig:$PKG_CONFIG_PATH

# Copy custom-built libvips libraries from libvips-builder stage
COPY --from=libvips-builder /usr/lib /usr/lib
COPY --from=libvips-builder /usr/bin /usr/bin
COPY --from=libvips-builder /usr/share /usr/share

COPY package*.json ./
# Tell sharp to use the system-wide libvips we just installed with HEIF support
ENV SHARP_IGNORE_GLOBAL_LIBVIPS=1
RUN npm ci

COPY . .
RUN npm run build

# Stage 3: Final production image
FROM node:22-bullseye-slim AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

# Create a non-root user
RUN addgroup --system --gid 1001 nodejs \
  && adduser --system --uid 1001 nextjs
USER nextjs

# Copy runtime dependencies and Next.js standalone output
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public

# Copy custom-built libvips libraries into the runtime image
COPY --from=libvips-builder /usr/lib /usr/lib
COPY --from=libvips-builder /usr/bin /usr/bin
COPY --from=libvips-builder /usr/share /usr/share

# Ensure data directories exist and are owned by nextjs user
RUN mkdir -p /app/data/uploads/photos /app/data/uploads/videos /app/data/uploads/music \
  && chown -R nextjs:nodejs /app/data

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