# ─── Stage 1: Install all workspace dependencies ─────────────────────────────
FROM node:22-slim AS deps

WORKDIR /app

COPY package.json package-lock.json ./
COPY packages/backend/package.json  ./packages/backend/package.json
COPY packages/frontend/package.json ./packages/frontend/package.json

RUN npm ci --ignore-scripts

# ─── Stage 2: Build the Preact frontend ──────────────────────────────────────
FROM deps AS build-frontend

COPY packages/frontend/ ./packages/frontend/

RUN npm run build -w frontend

# ─── Stage 3: Runtime image ───────────────────────────────────────────────────
FROM node:22-slim AS runtime

# Install Nginx
RUN apt-get update && apt-get install -y --no-install-recommends nginx \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# --- Dependencies ---
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/package.json ./package.json

# --- Backend ---
COPY packages/backend/ ./packages/backend/

# --- Frontend static files ---
COPY --from=build-frontend /app/packages/frontend/dist /usr/share/nginx/html

# --- Nginx config ---
COPY nginx.conf /etc/nginx/nginx.conf

# --- Entrypoint ---
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

# DATABASE_URL and OPENAI_API_KEY must be set when running the container.
ENV PORT=3000
ENV DATABASE_URL=postgres://user:password@localhost:5432/recommender
ENV OPENAI_API_KEY=your-openai-api-key-here

EXPOSE 80

ENTRYPOINT ["/entrypoint.sh"]
