# Use official Node.js runtime as the base image
FROM node:22.18.0 AS base

# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app

# Install build dependencies for native modules
RUN apt-get update && apt-get install -y \
    python3 \
    make \
    g++ \
    libsqlite3-dev \
    && rm -rf /var/lib/apt/lists/*

# Install pnpm globally
RUN npm install -g pnpm

# Copy package files and install all dependencies (including dev 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 || npm rebuild better-sqlite3

# Verify native bindings are compiled
RUN find /app/node_modules -name "better_sqlite3.node" -type f

# Database file will be created at runtime via docker-compose

# Create directories for media storage
RUN mkdir -p /app/data /app/media

# Build the application
RUN pnpm buildprod

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# Install FFmpeg for media file analysis
RUN apt-get update && apt-get install -y \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd --system --gid 1001 nodejs
RUN useradd --system --uid 1001 --gid nodejs nextjs

# Create media directories
RUN mkdir -p /app/data /app/media

# Ensure directories have correct permissions
RUN chown -R nextjs:nodejs /app/data /app/media

# Copy built application
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 node_modules to ensure 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 up volume for persistent data
VOLUME ["/app/data", "/app/media"]

# Switch to non-root user
USER nextjs

EXPOSE 3000

ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

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