import client from '../client';

export interface McpServerFull {
  id: string;
  name: string;
  description?: string;
  server_type: string;
  command?: string;
  args?: string[];
  env_vars?: Record<string, string>;
  url?: string;
  module_path?: string;
  is_active: boolean;
  tools?: McpToolDef[];
  linked_adb_id?: string;
  created_at?: string;
}

export interface McpToolDef {
  name: string;
  description?: string;
  input_schema?: Record<string, unknown>;
}

export interface McpServerPayload {
  name: string;
  description?: string | null;
  server_type: string;
  command?: string | null;
  args?: string[] | null;
  env_vars?: Record<string, string> | null;
  url?: string | null;
  module_path?: string | null;
  tools?: McpToolDef[] | null;
  linked_adb_id?: string | null;
}

export const mcpApi = {
  list: () =>
    client.get('/mcp/servers') as unknown as Promise<McpServerFull[]>,

  create: (body: McpServerPayload) =>
    client.post('/mcp/servers', body) as unknown as Promise<{ id: string; name: string; server_type: string }>,

  update: (id: string, body: McpServerPayload) =>
    client.put(`/mcp/servers/${id}`, body) as unknown as Promise<{ id: string; name: string; server_type: string }>,

  remove: (id: string) =>
    client.delete(`/mcp/servers/${id}`) as unknown as Promise<{ ok: boolean }>,

  toggle: (id: string) =>
    client.put(`/mcp/servers/${id}/toggle`) as unknown as Promise<{ ok: boolean; is_active: boolean }>,

  discoverTools: (id: string) =>
    client.post(`/mcp/servers/${id}/discover-tools`) as unknown as Promise<{ ok: boolean; discovered: number; total: number; tools: McpToolDef[] }>,

  updateTools: (id: string, tools: McpToolDef[]) =>
    client.put(`/mcp/servers/${id}/tools`, { tools }) as unknown as Promise<{ ok: boolean }>,

  upload: (id: string, file: File) => {
    const fd = new FormData();
    fd.append('file', file);
    return client.post(`/mcp/servers/${id}/upload`, fd, { headers: { 'Content-Type': 'multipart/form-data' } }) as unknown as Promise<{ ok: boolean; path: string }>;
  },

  linkAdb: (id: string, adbId: string) =>
    client.put(`/mcp/servers/${id}/link-adb?adb_id=${adbId}`) as unknown as Promise<{ ok: boolean }>,
};
