# Dockerfile para SmashPoint
# Multi-stage build para optimizar el tamano de la imagen

# ============================================
# Stage 1: Dependencias
# ============================================
FROM node:20-alpine AS deps
RUN apk add --no-cache libc6-compat openssl

WORKDIR /app

# Instalar pnpm
RUN corepack enable && corepack prepare pnpm@8.15.0 --activate

# Copiar archivos de configuracion de dependencias
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/web/package.json ./apps/web/
COPY packages/shared/package.json ./packages/shared/

# Instalar dependencias
RUN pnpm install --frozen-lockfile

# ============================================
# Stage 2: Builder
# ============================================
FROM node:20-alpine AS builder
RUN apk add --no-cache libc6-compat openssl

WORKDIR /app

# Instalar pnpm
RUN corepack enable && corepack prepare pnpm@8.15.0 --activate

# Copiar dependencias instaladas
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/web/node_modules ./apps/web/node_modules
COPY --from=deps /app/packages/shared/node_modules ./packages/shared/node_modules

# Copiar codigo fuente
COPY . .

# Generar cliente Prisma
RUN cd apps/web && pnpm db:generate

# Construir la aplicacion
ENV NEXT_TELEMETRY_DISABLED 1
RUN pnpm build

# ============================================
# Stage 3: Runner (Produccion)
# ============================================
FROM node:20-alpine AS runner
RUN apk add --no-cache openssl

WORKDIR /app

# Configurar entorno de produccion
ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

# Crear usuario no-root
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Copiar archivos de Next.js standalone (incluye node_modules necesarios)
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static

# Crear public folder
RUN mkdir -p ./apps/web/public && chown nextjs:nodejs ./apps/web/public

# Copiar schema de Prisma para migraciones
COPY --from=builder /app/apps/web/prisma ./apps/web/prisma

# Cambiar a usuario no-root
USER nextjs

# Exponer puerto
EXPOSE 3000

ENV PORT 3000
ENV HOSTNAME "0.0.0.0"

# Comando de inicio
CMD ["node", "server.js"]
