# ==================================================
# VIBN Frontend - Next.js on Coolify
# ==================================================

FROM node:22-alpine AS base

FROM base AS deps
RUN apk add --no-cache libc6-compat python3 make g++
WORKDIR /app
COPY package*.json ./
RUN npm install --legacy-peer-deps --ignore-scripts

FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
# Force Prisma to generate linux-musl-openssl-3.0.x binary (Alpine 3.21 uses OpenSSL 3.x)
ENV PRISMA_CLI_BINARY_TARGETS=linux-musl-openssl-3.0.x

# Sentry: NEXT_PUBLIC_SENTRY_DSN gets inlined into the client bundle
# during `npm run build` (any NEXT_PUBLIC_* var must be present at
# build time, not just runtime). SENTRY_AUTH_TOKEN is consumed by
# withSentryConfig to upload source maps to Sentry as part of the
# build. Coolify already marks both as is_buildtime:true and passes
# them via --build-arg; these ARG lines accept them and re-export
# as ENV so `next build` and the Sentry wrapper see them.
ARG NEXT_PUBLIC_SENTRY_DSN
ARG SENTRY_AUTH_TOKEN
ENV NEXT_PUBLIC_SENTRY_DSN=$NEXT_PUBLIC_SENTRY_DSN
ENV SENTRY_AUTH_TOKEN=$SENTRY_AUTH_TOKEN

RUN npx prisma generate
RUN npm run build

FROM base AS runner
WORKDIR /app

# Install OpenSSL 3.x and Prisma CLI at the correct version
RUN apk add --no-cache openssl && npm install -g prisma@5

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1

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

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

COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma
COPY --from=builder /app/node_modules/@next-auth ./node_modules/@next-auth
COPY --from=builder /app/prisma ./prisma

# Scaffold templates are read at runtime via fs — must be in the runner image
COPY --from=builder /app/lib/scaffold ./lib/scaffold

# Copy and set up entrypoint
COPY --chown=nextjs:nodejs entrypoint.sh ./entrypoint.sh

USER root
RUN chmod +x ./entrypoint.sh

USER nextjs

EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"

# Use 127.0.0.1 explicitly — "localhost" resolves to ::1 (IPv6) first
# inside Alpine, but Next.js only binds 0.0.0.0 (IPv4), causing
# Coolify's health-check wget to get "Connection refused" even though
# the server is healthy. start-period covers the DB-init DDL in
# entrypoint.sh (~5-10s) plus Next.js startup (~1-2s).
HEALTHCHECK --interval=10s --timeout=5s --start-period=60s --retries=10 \
  CMD wget -qO- http://127.0.0.1:3000/ > /dev/null || exit 1

ENTRYPOINT ["./entrypoint.sh"]

