FROM node:24-alpine

WORKDIR /app

RUN apk add --no-cache openssl

ARG NPM_REGISTRY=https://registry.npmjs.org

COPY package.json package-lock.json .npmrc ./
COPY apps/sso-core/package.json ./apps/sso-core/
COPY apps/api-gateway/package.json ./apps/api-gateway/
COPY apps/frontend/package.json ./apps/frontend/
COPY apps/docs/package.json ./apps/docs/

RUN --mount=type=cache,target=/root/.npm \
  npm config set registry "${NPM_REGISTRY}" && \
  for i in 1 2 3 4 5; do \
    echo "npm ci: попытка $i/5" && \
    npm ci --no-audit --no-fund && exit 0; \
    echo "npm ci: ошибка сети, повтор через $((i * 15)) сек..."; \
    sleep $((i * 15)); \
  done; \
  echo "npm ci: все попытки исчерпаны"; \
  exit 1

COPY apps ./apps
COPY shared ./shared
COPY tsconfig.base.json ./

ENV DATABASE_URL="postgresql://lendry:lendry_password@postgres:5432/lendry_id?schema=public"
ENV JWT_ACCESS_SECRET="docker-access-secret"
ENV JWT_REFRESH_SECRET="docker-refresh-secret"
ENV DATA_ENCRYPTION_KEY="docker-data-encryption-secret-change-me"
ENV REDIS_URL="redis://redis:6379"
ENV GRPC_URL="0.0.0.0:50051"
ENV HTTP_PORT="3001"

RUN npm --workspace @lendry/sso-core run prisma:generate \
  && npm --workspace @lendry/sso-core run proto:generate \
  && npm --workspace @lendry/sso-core run build

COPY apps/sso-core/docker-entrypoint.sh /docker-entrypoint.sh
RUN sed -i 's/\r$//' /docker-entrypoint.sh && chmod +x /docker-entrypoint.sh

EXPOSE 3001 50051

ENTRYPOINT ["/docker-entrypoint.sh"]
