# Base image
FROM node:22-alpine

# Install dependencies
WORKDIR /app

# Install curl and wget for healthchecks
RUN apk add --no-cache curl wget

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci --only=production

# Copy application code
COPY . .

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

# Create non-root user
RUN addgroup -g 1001 -S mcp && \
    adduser -u 1001 -S mcp -G mcp && \
    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"]
