FROM node:22-alpine AS base

WORKDIR /app

# Install deps (all workspaces)
COPY package.json package-lock.json* ./
COPY shared/package.json shared/
COPY server/package.json server/
RUN npm install --ignore-scripts

# Rebuild native modules (better-sqlite3)
RUN npm rebuild better-sqlite3

# Copy all source
COPY . .

# Build Astro SSR site
RUN npm run build

# ── Production stage ──
FROM node:22-alpine AS runtime
WORKDIR /app

# Install tsx globally for running the orchestrator
RUN npm install -g tsx

COPY --from=base /app/node_modules ./node_modules
COPY --from=base /app/shared ./shared
COPY --from=base /app/server ./server
COPY --from=base /app/dist ./dist
COPY --from=base /app/package.json ./
COPY --from=base /app/site-context.json ./
COPY --from=base /app/content ./content
COPY --from=base /app/content ./content-seed
COPY --from=base /app/config ./config

COPY entrypoint.sh /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh

ENV HOST=0.0.0.0
ENV PORT=4321
ENV ORCHESTRATOR_PORT=3001
ENV REPO_ROOT=/app
ENV NODE_ENV=production

# Expose both ports
EXPOSE 4321 3001

ENTRYPOINT ["/app/entrypoint.sh"]
