# Use a smaller base image for the final runtime
FROM node:22.18.0-alpine AS base

# Build stage
FROM base AS builder
WORKDIR /app

# Install build dependencies for native modules
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    sqlite-dev \
    ffmpeg-dev

# Install pnpm globally
RUN npm install -g pnpm

# Copy package files and install all dependencies
COPY package.json package-lock.json ./
RUN pnpm install 

# Copy source code
COPY . .

# Rebuild better-sqlite3 to ensure native bindings are compiled correctly
RUN pnpm rebuild better-sqlite3

# Build the application
RUN pnpm buildprod

# Production stage
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Install only runtime dependencies
RUN apk add --no-cache \
    ffmpeg \
    sqlite \
    && rm -rf /var/cache/apk/*

# Create user
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 --ingroup nodejs nextjs

# Create necessary directories
RUN mkdir -p /app/data /app/media /app/public/thumbnails

# Copy only the necessary files from builder
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# Copy the entire node_modules to ensure all native bindings are available
COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules

# Rebuild native bindings for the production environment
RUN npm rebuild better-sqlite3

# Set correct permissions
RUN chown -R nextjs:nodejs /app/data /app/media /app/public

# Switch to non-root user
USER nextjs

EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

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