# ─── 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

# Next.js standalone creates a subdirectory named after the project folder.
# We flatten it to a known location so the runner doesn't depend on the name.
RUN echo "=== Standalone output structure ===" && \
    ls -la /app/.next/standalone/ && \
    mkdir -p /app/.next/standalone-export && \
    cp -r /app/.next/standalone/*/ /app/.next/standalone-export/ && \
    ls -la /app/.next/standalone-export/

# ─── 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 is now directly in /app)
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone-export/ ./

# Copy static assets (images, fonts, etc.)
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"]
