# syntax=docker/dockerfile:1

# --- Bun on Alpine for build ---
FROM oven/bun:alpine AS base

# --- deps: install node_modules with Bun ---
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Copy package + whichever Bun lock file you have (optional)
COPY package.json bun.lockb* bun.lock* ./
COPY tsconfig.base.json ./
COPY apps/next/package.json ./apps/next/

# If bun.lockb exists, enforce frozen; otherwise install and generate it
RUN if [ -f bun.lockb ]; then \
      bun install --frozen-lockfile; \
    else \
      bun install; \
    fi

# --- builder: build Next.js with Bun ---
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/tsconfig.base.json ./tsconfig.base.json
COPY apps/next ./apps/next
COPY packages ./packages
WORKDIR /app/apps/next
ENV NEXT_TELEMETRY_DISABLED=1
RUN bun run build

# --- runner: Node on Alpine to run server.js ---
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

# non-root user
RUN addgroup -S nodejs -g 1001 && adduser -S nextjs -u 1001
COPY --from=builder /app/apps/next/public ./public
RUN mkdir .next && chown -R nextjs:nodejs .next
RUN mkdir -p .next/cache && chown -R nextjs:nodejs .next

# Next standalone output
COPY --from=builder /app/apps/next/.next/standalone ./
COPY --from=builder /app/apps/next/.next/static ./.next/static
COPY --from=builder /app/node_modules ./node_modules

USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME=0.0.0.0
CMD ["node", "server.js"]
