# Stage 1: Fetch platform server package from git
FROM alpine:3.20 AS platform
RUN apk add --no-cache git
ARG PLATFORM_REPO=https://git.spatulaa.com/MayaTheShy/cc-platform-core.git
ARG PLATFORM_BRANCH=master
RUN git clone --depth 1 --branch "$PLATFORM_BRANCH" "$PLATFORM_REPO" /src \
    && rm -rf /src/server/node_modules /src/.git

# Stage 2: Node.js backend
FROM node:18-alpine

WORKDIR /app

# Copy platform server package from the git-clone stage
COPY --from=platform /src/server /app/platform-server/

# Copy package files
COPY package*.json ./

# Rewrite file: dependency to use the local copy inside the container
RUN sed -i 's|file:../../cc-platform-core/server|file:./platform-server|' package.json \
    && rm -f package-lock.json

# Install dependencies
RUN npm install --omit=dev

# Copy all server code
COPY . .

# Expose ports
EXPOSE 3001 3002

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3001/api/turtles', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# Start server
CMD ["node", "server.js"]
