# Stage 1: Build the Next.js app
# sharp 0.34+ bundles prebuilt libvips with HEIF support, no custom build needed
FROM node:22-bullseye-slim AS builder

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

# Stage 2: 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"

# Install gosu for entrypoint
RUN apt-get update && apt-get install -y --no-install-recommends \
    gosu \
    && rm -rf /var/lib/apt/lists/*

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

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

# Entrypoint script to fix volume permissions at startup
RUN printf '#!/bin/sh\nmkdir -p /app/data/uploads/photos /app/data/uploads/videos /app/data/uploads/music\nchown -R nextjs:nodejs /app/data 2>/dev/null || true\nexec gosu nextjs node server.js\n' > /app/entrypoint.sh \
  && chmod +x /app/entrypoint.sh

EXPOSE 3000
CMD ["/app/entrypoint.sh"]
