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

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

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

ENTRYPOINT ["./entrypoint.sh"]

