FROM node:22-alpine
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH

# Copie et installation
COPY . .
RUN npm install
RUN npx prisma generate
RUN npm run build

EXPOSE 3001
ENV PORT=3001

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
RUN chown -R nextjs:nodejs /app

USER nextjs

HEALTHCHECK --interval=15s --timeout=5s --start-period=60s --retries=5 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3001/api/health || exit 1

# On lance directement via npm (avec push de la BD si besoin, ou juste start)
CMD ["sh", "-c", "npx prisma db push --schema=prisma/schema.prisma --accept-data-loss && (node ../scripts/ensure-admin.cjs || node scripts/ensure-admin.cjs || true) && npm start"]
