# ─── Stage 1: Builder (install ALL deps + build) ────────────────────────────
FROM node:20-alpine AS builder
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Copy dependency files first (cache layer)
COPY package.json package-lock.json ./
RUN npm ci && npm cache clean --force

# Copy source code
COPY . .

# Build requires these env vars for static analysis
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

RUN npm run build

# Flatten standalone output — find the single subdir Next.js creates
RUN set -e && \
    echo "=== Standalone output ===" && \
    ls -la /app/.next/standalone/ && \
    mkdir -p /app/.next/standalone-export && \
    STANDALONE_DIR=$(find /app/.next/standalone -maxdepth 1 -mindepth 1 -type d | head -1) && \
    echo "Copying from: $STANDALONE_DIR" && \
    cp -r "$STANDALONE_DIR"/* /app/.next/standalone-export/ && \
    ls -la /app/.next/standalone-export/ && \
    test -f /app/.next/standalone-export/server.js && echo "✅ server.js found" || (echo "❌ server.js NOT FOUND" && exit 1)

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

ENV NODE_ENV=production
ENV PORT=3020
ENV HOSTNAME=0.0.0.0

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

# Copy flattened standalone output (server.js directly in /app)
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone-export/ ./

# Copy static assets
COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3020

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3020/api/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})" || exit 1

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