/**
 * Load MCP server configurations from DB for the Claude Agent SDK.
 * Converts DB mcp_servers rows into SDK McpServerConfig records.
 */

import { mcpServerRepo } from '@/lib/database/repositories/mcp-server.repo'
import type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk'

interface StdioConfig {
  command?: string
  args?: string[]
  env?: Record<string, string>
}

interface SseHttpConfig {
  url?: string
  headers?: Record<string, string>
}

/**
 * Load all enabled MCP servers from the DB and convert to SDK format.
 */
export function loadMcpServersFromDb(userId?: string): Record<string, McpServerConfig> {
  const rows = userId
    ? mcpServerRepo.listEnabledByUser(userId)
    : mcpServerRepo.listEnabledAnonymous()

  const servers: Record<string, McpServerConfig> = {}

  for (const row of rows) {
    let parsed: Record<string, unknown> = {}
    try { parsed = JSON.parse(row.config) } catch (err) { console.warn('[forge] Failed to parse MCP server config:', row.name, err); continue }

    switch (row.protocol) {
      case 'stdio': {
        const cfg = parsed as StdioConfig
        if (!cfg.command) continue
        servers[row.name] = {
          type: 'stdio',
          command: cfg.command,
          args: cfg.args,
          env: cfg.env,
        }
        break
      }
      case 'sse': {
        const cfg = parsed as SseHttpConfig
        if (!cfg.url) continue
        servers[row.name] = {
          type: 'sse',
          url: cfg.url,
          headers: cfg.headers,
        }
        break
      }
      case 'http': {
        const cfg = parsed as SseHttpConfig
        if (!cfg.url) continue
        servers[row.name] = {
          type: 'http',
          url: cfg.url,
          headers: cfg.headers,
        }
        break
      }
    }
  }

  return servers
}
