# Multi-stage Dockerfile for Next.js Landing Page

# Stage 1: Dependencies
FROM node:20-alpine AS deps
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

# Copy workspace configuration
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./

# Copy landing package.json
COPY apps/landing/package.json ./apps/landing/

# Copy database package (workspace dependency)
COPY packages/database/package.json ./packages/database/

# Install dependencies
RUN pnpm install --frozen-lockfile

# Stage 2: Builder
FROM node:20-alpine AS builder
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

# Copy dependencies from deps stage
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/landing/node_modules ./apps/landing/node_modules
COPY --from=deps /app/packages/database/node_modules ./packages/database/node_modules

# Copy workspace files
COPY pnpm-workspace.yaml package.json pnpm-lock.yaml ./

# Copy database package
COPY packages/database ./packages/database

# Copy landing app
COPY apps/landing ./apps/landing

# Set working directory to landing
WORKDIR /app/apps/landing

# Build Next.js application
ENV NEXT_TELEMETRY_DISABLED=1
RUN pnpm build

# Stage 3: Production Runner
FROM node:20-alpine AS runner
WORKDIR /app

# Install pnpm
RUN npm install -g pnpm@10.11.0

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

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

# Copy workspace configuration
COPY --from=builder /app/pnpm-workspace.yaml ./
COPY --from=builder /app/package.json ./
COPY --from=builder /app/pnpm-lock.yaml ./

# Copy database package
COPY --from=builder /app/packages/database ./packages/database

# Copy built Next.js application
COPY --from=builder --chown=nextjs:nodejs /app/apps/landing/.next ./apps/landing/.next
COPY --from=builder /app/apps/landing/package.json ./apps/landing/
COPY --from=builder /app/apps/landing/public ./apps/landing/public

# Copy node_modules for runtime
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/apps/landing/node_modules ./apps/landing/node_modules
COPY --from=builder /app/packages/database/node_modules ./packages/database/node_modules

USER nextjs

EXPOSE 3000

ENV PORT=3000

WORKDIR /app/apps/landing

CMD ["pnpm", "start"]
