FROM node:20-alpine

WORKDIR /build

# Copy both cf-api and common
COPY cf-api ./cf-api
COPY common ./common

# Build common package first (since cf-api depends on it)
WORKDIR /build/common
RUN npm ci && npm run build

# Install ALL dependencies for cf-api (including dev dependencies)
WORKDIR /build/cf-api
RUN npm ci

# Replace the common package from registry with local build
RUN rm -rf node_modules/@codeflash-ai/common && \
    cp -r /build/common node_modules/@codeflash-ai/

# Clean dist folder before build to avoid nested dist directories
RUN rm -rf dist

# Build TypeScript
RUN npm run build

# Production stage
FROM node:20-alpine

WORKDIR /app

# Copy the built files
COPY --from=0 /build/cf-api/dist ./dist
COPY --from=0 /build/cf-api/package.json ./package.json
COPY --from=0 /build/cf-api/package-lock.json ./package-lock.json
COPY --from=0 /build/cf-api/resend ./resend
COPY --from=0 /build/cf-api/github ./github

# Copy common package to parent directory (matching Azure structure)
COPY --from=0 /build/common ../common

# Copy already installed node_modules from build stage
COPY --from=0 /build/cf-api/node_modules ./node_modules

# Copy node_modules into dist to match Azure deployment structure
# Use -L to follow symlinks and avoid broken nested structures
RUN cp -rL node_modules dist/ 2>/dev/null || cp -r node_modules dist/

EXPOSE 3001

CMD ["npm", "start"]
