# Base stage with Node.js
FROM node:20-slim AS base

# Setup environment for pnpm
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable

WORKDIR /app

# Install sharp dependencies in a separate stage
FROM base AS sharp
# Install sharp for production
RUN pnpm add sharp

# Install dependencies and build the project
FROM base AS builder
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable

# Install Git to clone the repository
RUN apt update && apt-get install git -y

# Clone the repository (you can replace this with a COPY if local)
RUN git clone https://github.com/designcombo/react-video-editor.git .

# Install the project's dependencies
RUN pnpm install

# Build the application in standalone mode
RUN pnpm run build

# Production stage
FROM base AS runner
WORKDIR /app
ENV NODE_ENV production

# Create non-root user for security
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copy the public folder from the builder stage
COPY --from=builder /app/public ./public

# Set correct permissions for prerender cache
RUN mkdir -p .next/cache
RUN chown -R nextjs:nodejs .next
RUN chmod -R 777 .next/cache

# Copy the standalone build files from the builder stage
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# Copy node_modules from the sharp stage (optional)
COPY --from=sharp /app/node_modules ./node_modules

# Switch to non-root user
USER nextjs

# Expose the port
EXPOSE 7860

# Set environment variables
ENV HOSTNAME "0.0.0.0"
ENV PORT 7860


CMD ["pnpm", "dev"]