# Base stage with system dependencies
FROM node:20 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
RUN npm install -g pnpm

WORKDIR /app

# Copy package files for dependency installation
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
COPY apps/web/package.json apps/web/
COPY apps/service/package.json apps/service/
COPY apps/cli/package.json apps/cli/
COPY packages/eslint-config/package.json packages/eslint-config/
COPY packages/typescript-config/package.json packages/typescript-config/
COPY packages/ui/package.json packages/ui/

# Dependencies stage
FROM base AS dependencies

# 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 application
FROM dependencies AS builder

# Copy all source code
COPY . .

# Build all applications
RUN pnpm run build

# Production dependencies stage
FROM base AS prod-dependencies

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

# Production stage
FROM node:20-slim AS production

# Install runtime system dependencies
RUN apt-get update && apt-get install -y \
    handbrake-cli \
    sqlite3 \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# Install pnpm
RUN npm install -g pnpm

WORKDIR /app

# Copy package files
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./
COPY apps/web/package.json apps/web/
COPY apps/service/package.json apps/service/
COPY apps/cli/package.json apps/cli/
COPY packages/eslint-config/package.json packages/eslint-config/
COPY packages/typescript-config/package.json packages/typescript-config/
COPY packages/ui/package.json packages/ui/

# Copy production dependencies
COPY --from=prod-dependencies /app/node_modules ./node_modules

# Copy built applications
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 source files for Next.js
COPY apps/web/next.config.ts apps/web/
COPY apps/web/next.config.js apps/web/

# Expose ports
EXPOSE 3000 3001 3002

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