# --- STAGE 1: Base ---
FROM node:20-alpine AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /app

# --- STAGE 2: Build everything ---
FROM base AS build
COPY . .
RUN pnpm install --frozen-lockfile
RUN pnpm turbo run build

# --- STAGE 3: Extract for Production ---
# This "flattens" the api and its node_modules into a standalone folder
RUN pnpm deploy --filter=api --prod /prod/api

# --- STAGE 4: Runner ---
FROM node:20-alpine AS runner
WORKDIR /app

# Copy the standalone API (includes its own local node_modules)
COPY --from=build /prod/api .

# Copy the web dist into the location the API expects
# Based on your code, it looks for ../web-dist or ./web-dist
COPY --from=build /app/apps/web/dist ./web-dist

# We need the shared package if the API imports it directly as source
# But pnpm deploy usually handles the shared package if it's built
COPY --from=build /app/packages/shared ./packages/shared

EXPOSE 3000
ENV NODE_ENV=production

# Since we are now inside the "api" folder essentially:
CMD ["node", "dist/index.js"]