FROM node:20-bookworm AS builder

WORKDIR /app

RUN corepack enable && corepack prepare npm@10.5.0 --activate

COPY package.json package-lock.json turbo.json tsconfig.base.json ./
COPY apps ./apps
COPY packages ./packages
COPY config ./config

# These URLs are read by Next.js config during `next build`, so the production
# image must bake Docker-network service URLs instead of localhost defaults.
ARG API_INTERNAL_URL=http://api:4000/api/v1
ARG DASHBOARD_INTERNAL_URL=http://dashboard:3001
ARG ADMIN_INTERNAL_URL=http://admin:3002

# NEXT_PUBLIC_* vars must be present at build time — they are inlined into JS bundles
ARG NEXT_PUBLIC_API_URL
ARG NEXT_PUBLIC_HOMEPAGE_URL
ARG NEXT_PUBLIC_STOREFRONT_URL
ARG NEXT_PUBLIC_DASHBOARD_URL
ARG NEXT_PUBLIC_ADMIN_URL

# SITE_ORIGIN is the canonical public origin for robots.txt, sitemap, and metadata.
# Required in production — must be an absolute https:// URL with no path, query, or fragment.
ARG SITE_ORIGIN

ENV API_INTERNAL_URL=$API_INTERNAL_URL \
    DASHBOARD_INTERNAL_URL=$DASHBOARD_INTERNAL_URL \
    ADMIN_INTERNAL_URL=$ADMIN_INTERNAL_URL \
    NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL \
    NEXT_PUBLIC_HOMEPAGE_URL=$NEXT_PUBLIC_HOMEPAGE_URL \
    NEXT_PUBLIC_STOREFRONT_URL=$NEXT_PUBLIC_STOREFRONT_URL \
    NEXT_PUBLIC_DASHBOARD_URL=$NEXT_PUBLIC_DASHBOARD_URL \
    NEXT_PUBLIC_ADMIN_URL=$NEXT_PUBLIC_ADMIN_URL \
    SITE_ORIGIN=$SITE_ORIGIN

RUN npm ci --include=optional
RUN npm run db:generate
RUN npm run build

FROM node:20-bookworm AS runner

WORKDIR /app

ENV NODE_ENV=production \
    NPM_CONFIG_UPDATE_NOTIFIER=false

RUN corepack enable && corepack prepare npm@10.5.0 --activate \
  && groupadd --system --gid 10001 app \
  && useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app \
  && mkdir -p /var/lib/rentaldrivego/storage/public /var/lib/rentaldrivego/storage/private /tmp/rentaldrivego \
  && chown -R app:app /app /var/lib/rentaldrivego /tmp/rentaldrivego

COPY --from=builder --chown=app:app /app/package.json /app/package-lock.json /app/turbo.json /app/tsconfig.base.json ./
COPY --from=builder --chown=app:app /app/node_modules ./node_modules
COPY --from=builder --chown=app:app /app/apps ./apps
COPY --from=builder --chown=app:app /app/packages ./packages
COPY --from=builder --chown=app:app /app/config ./config
COPY --chown=root:root docker/entrypoint.production.sh /usr/local/bin/rdg-entrypoint.sh

RUN chmod 755 /usr/local/bin/rdg-entrypoint.sh

ENTRYPOINT ["/usr/local/bin/rdg-entrypoint.sh"]

EXPOSE 3000 3001 3002 3004 4000

CMD ["npm", "run", "start", "--workspace", "@rentaldrivego/api"]
