# Multi-stage Dockerfile for garage-erp dashboard (Coolify).
# Monorepo: turborepo + pnpm; @garage/dashboard depends on @garage/api.
# Build context = garage-erp/ (repo root for this app).

# ────────────────────────────────────────────────────────────
# Stage 1: base — pnpm via corepack, shared layer
# ────────────────────────────────────────────────────────────
FROM node:22-alpine AS base
RUN corepack enable && corepack prepare pnpm@9.0.0 --activate
WORKDIR /app

# ────────────────────────────────────────────────────────────
# Stage 2: deps — install all workspace deps
# ────────────────────────────────────────────────────────────
FROM base AS deps
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
COPY apps/dashboard/package.json ./apps/dashboard/
COPY packages/api/package.json ./packages/api/
COPY packages/ui/package.json ./packages/ui/
COPY packages/eslint-config/package.json ./packages/eslint-config/
COPY packages/typescript-config/package.json ./packages/typescript-config/
# Force dev deps even when Coolify injects NODE_ENV=production at build time.
# Tailwind / postcss / next types are devDependencies — required by `next build`.
RUN NODE_ENV=development pnpm install --frozen-lockfile --prod=false

# ────────────────────────────────────────────────────────────
# Stage 3: builder — build dashboard with standalone output
# ────────────────────────────────────────────────────────────
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/dashboard/node_modules ./apps/dashboard/node_modules
COPY --from=deps /app/packages/api/node_modules ./packages/api/node_modules
COPY . .

ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production

# Build only the dashboard (turbo handles @garage/api codegen via prebuild hook)
RUN pnpm --filter @garage/dashboard build

# ────────────────────────────────────────────────────────────
# Stage 4: runner — minimal runtime, standalone Next.js
# ────────────────────────────────────────────────────────────
FROM node:22-alpine AS runner
WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

# curl for Coolify healthcheck (busybox wget prefers IPv6 ::1 and fails)
RUN apk add --no-cache curl

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

# Standalone server + traced node_modules
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/standalone ./
# Static assets
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/.next/static ./apps/dashboard/.next/static
# Public assets (logos, etc.)
COPY --from=builder --chown=nextjs:nodejs /app/apps/dashboard/public ./apps/dashboard/public

USER nextjs

EXPOSE 3000

# Standalone entry is at apps/dashboard/server.js after copy
CMD ["node", "apps/dashboard/server.js"]
