// CloseBot API Client — Reused patterns from closebot-mcp
const BASE_URL = 'https://api.closebot.com';

export class CloseBotClient {
  private apiKey: string;

  constructor(apiKey?: string) {
    this.apiKey = apiKey || process.env.CLOSEBOT_API_KEY || '';
  }

  get isConfigured(): boolean {
    return this.apiKey.length > 0;
  }

  private get headers(): Record<string, string> {
    return {
      'X-CB-KEY': this.apiKey,
      'Content-Type': 'application/json',
      Accept: 'application/json',
    };
  }

  async get<T = unknown>(path: string, query?: Record<string, unknown>): Promise<T> {
    const url = new URL(path, BASE_URL);
    if (query) {
      for (const [k, v] of Object.entries(query)) {
        if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
      }
    }
    const res = await fetch(url.toString(), { headers: this.headers });
    if (!res.ok) throw new Error(`CloseBot API ${res.status}: ${await res.text()}`);
    return res.json();
  }

  async post<T = unknown>(path: string, body?: unknown): Promise<T> {
    const res = await fetch(`${BASE_URL}${path}`, {
      method: 'POST',
      headers: this.headers,
      body: body ? JSON.stringify(body) : undefined,
    });
    if (!res.ok) throw new Error(`CloseBot API ${res.status}: ${await res.text()}`);
    const text = await res.text();
    return text ? JSON.parse(text) : ({} as T);
  }

  // --- Convenience methods ---

  async listBots() {
    return this.get<Array<{ id: string; name: string; category: string; locked: boolean; favorited: boolean; versions: Array<{ version: string; published: boolean }>; sources: Array<{ id: string; name: string }>; modifiedAt: string }>>('/bot');
  }

  async getBot(id: string) {
    return this.get(`/bot/${id}`);
  }

  async getAgencySummary(sourceId?: string) {
    return this.get('/botMetric/agencySummary', { sourceId });
  }

  async getBookingGraph(start?: string, end?: string, resolution = 'daily') {
    return this.get('/botMetric/bookingGraph', { start, end, resolution });
  }

  async getLeaderboard(metric = 'responses', numTopLeaders = 10) {
    return this.get('/botMetric/leaderboard', { metric, numTopLeaders });
  }

  async listSources() {
    return this.get<Array<{ id: string; name: string; type: string }>>('/agency/source');
  }

  async sendWebhookEvent(sourceId: string, payload: unknown) {
    return this.post(`/webhook/event/${sourceId}`, payload);
  }

  async listLeads(opts?: { offset?: number; maxCount?: number }) {
    return this.get('/lead', opts);
  }

  async searchLeads(query: Record<string, unknown>) {
    return this.post('/lead/search', query);
  }

  async testConnection(): Promise<boolean> {
    try {
      await this.get('/agency/current');
      return true;
    } catch {
      return false;
    }
  }
}

let _client: CloseBotClient | null = null;
export function getCloseBotClient(): CloseBotClient {
  if (!_client) _client = new CloseBotClient();
  return _client;
}
