# 1. Base Image: Wir nehmen "slim" statt "alpine" (baut oft schneller)
FROM node:20-slim AS base

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

# 2. Dependencies Stage (mit Cache!)
FROM base AS deps
WORKDIR /app

COPY package.json pnpm-lock.yaml ./

# TRICK 1: Cache Mount für pnpm store
# Das verhindert, dass Pakete jedes Mal neu aus dem Internet geladen werden
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
    pnpm install --frozen-lockfile --unsafe-perm

# 3. Builder Stage (mit Cache!)
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Environment Variablen für Build
ARG NEXT_PUBLIC_SUPABASE_URL
ARG NEXT_PUBLIC_SUPABASE_ANON_KEY
ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL
ENV NEXT_PUBLIC_SUPABASE_ANON_KEY=$NEXT_PUBLIC_SUPABASE_ANON_KEY
ENV NEXT_TELEMETRY_DISABLED 1

# TRICK 2: Cache Mount für Next.js Cache (.next/cache)
# Das ist der wichtigste Teil! Next.js muss nicht alles neu kompilieren.
RUN --mount=type=cache,target=/app/.next/cache \
    pnpm run build

# 4. Runner Stage
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

# Install curl for healthcheck
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 7777
ENV PORT 7777
ENV HOSTNAME "0.0.0.0"

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:7777/api/health || exit 1

CMD ["node", "server.js"]