# Base stage with system dependencies and pnpm
FROM node:20-slim AS base

# Install system dependencies including HandBrakeCLI, SQLite, and FFmpeg
RUN apt-get update && apt-get install -y \
    handbrake-cli \
    sqlite3 \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# Install pnpm globally
RUN npm install -g pnpm

WORKDIR /app

# Dependencies stage - install all dependencies
FROM base AS dependencies

# Copy package files for dependency installation
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
COPY apps/*/package.json ./apps/
COPY packages/*/package.json ./packages/

# Install all dependencies (including dev dependencies for building)
RUN pnpm install --frozen-lockfile

# Development stage
FROM dependencies AS development

# Copy all source code
COPY . .

# Expose ports
EXPOSE 3000 3001 3002

# Set the CLI as the default entrypoint for development
ENTRYPOINT ["pnpm", "run", "cli"]
CMD []

# Builder stage - builds the applications
FROM dependencies AS builder

# Copy all source code
COPY . .

# Build all applications
RUN pnpm run build

# Production stage - final runtime image
FROM base AS production

# Copy package files for production dependencies
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
COPY apps/*/package.json ./apps/
COPY packages/*/package.json ./packages/

# Install only production dependencies
RUN pnpm install --frozen-lockfile --prod

# Copy built applications from builder stage
COPY --from=builder /app/apps/web/.next ./apps/web/.next
COPY --from=builder /app/apps/web/public ./apps/web/public
COPY --from=builder /app/apps/service/dist ./apps/service/dist
COPY --from=builder /app/apps/cli/dist ./apps/cli/dist

# Copy necessary config files for Next.js
COPY apps/web/next.config.ts apps/web/next.config.js ./apps/web/

# Expose ports
EXPOSE 3000 3001 3002

# Default command runs all services in production
CMD ["pnpm", "start"]