# Base image
FROM node:20-alpine

# Install dependencies
WORKDIR /app

# Install curl, wget, and openssl for healthchecks and Prisma runtime
RUN apk add --no-cache curl wget openssl libc6-compat

# Copy package files
COPY package*.json ./

# Install all dependencies (including dev for prisma generate)
RUN npm ci

# Copy application code
COPY . .

# Copy Prisma schema and generate client
COPY prisma ./prisma
RUN npx prisma generate

# Prune devDependencies after generating Prisma client
RUN npm prune --omit=dev

# Create non-root user
RUN addgroup -g 1001 -S mcp && \
    adduser -u 1001 -S mcp -G mcp

# Create database directory
RUN mkdir -p /app/db && \
    chown -R mcp:mcp /app

USER mcp

WORKDIR /app

# Expose port for SSE mode (3001)
EXPOSE 3001

# Create startup script
RUN printf '%s\n' '#!/bin/sh' \
    'if [ "${MCP_MODE}" = "sse" ]; then' \
    '    echo "Starting MCP server in SSE mode on port ${PORT:-3001}"' \
    '    exec node index-sse.js' \
    'else' \
    '    echo "Starting MCP server in stdio mode"' \
    '    exec node index.js' \
    'fi' > /app/start.sh && chmod +x /app/start.sh

# Health check - works for both modes
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
  CMD if [ "${MCP_MODE}" = "sse" ]; then wget --spider -q http://localhost:${PORT:-3001}/ 2>/dev/null || exit 1; else node -e "console.log('healthy')" || exit 1; fi

# Start MCP server with mode selection
CMD ["/app/start.sh"]
