# ── Falah Mobile — Production Dockerfile ──────────────────────────────
# Requires npm run build to be run first on the host (Next.js standalone)
# Build sequence:
#   cd /app && npm ci && npm run build
#   docker build -t falah-mobile:latest .

FROM node:20-alpine

RUN apk add --no-cache openssl ca-certificates curl

WORKDIR /app

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

# Copy standalone build (pre-built outside Docker)
COPY .next/standalone/ ./
COPY .next/static ./.next/static
COPY public ./public

# Install production dependencies inside Docker
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY prisma ./prisma

# Fix Turbopack's hashed Prisma client path (if .next inside standalone)
RUN if [ -d "/app/.next/node_modules/@prisma" ]; then \
      for d in /app/.next/node_modules/@prisma/client-*; do \
        name=$(basename "$d"); \
        rm -f "/app/node_modules/@prisma/$name" 2>/dev/null; \
        cp -r /app/node_modules/@prisma/client "/app/node_modules/@prisma/$name"; \
      done; \
    fi

RUN mkdir -p /app/data && chown nextjs:nodejs /app/data

# Fix permissions so nextjs user can run prisma CLI and read schema
RUN chown -R nextjs:nodejs /app/node_modules/@prisma /app/node_modules/prisma /app/node_modules/.prisma /app/prisma 2>/dev/null || true

# Startup script — migrate volumes DB then launch server
COPY start.sh /app/start.sh
RUN chmod +x /app/start.sh

# ── Docker HEALTHCHECK ──────────────────────────────────────────
# Auto-restarts container if health endpoint fails 3 times (30s interval, 10s timeout)
HEALTHCHECK --interval=30s --timeout=10s --start-period=15s --retries=3 \
  CMD curl -sf http://localhost:3000/mobile/api/health || exit 1

USER nextjs
EXPOSE 3000

ENV NODE_ENV=production
ENV DATABASE_URL="file:/app/data/dev.db"

CMD ["/app/start.sh"]
