import { apiGet } from './client';
import type { Conversation, Message, MessageSearchResponse, SearchMode } from '@/types';

export async function fetchConversations(deviceId?: string): Promise<Conversation[]> {
  try {
    const qs = deviceId ? `?deviceId=${encodeURIComponent(deviceId)}` : '';
    return await apiGet<Conversation[]>(`/my/messages/conversations${qs}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchConversations failed');
  }
}

export async function fetchThread(conversationId: string, limit = 100, since?: string): Promise<Message[]> {
  try {
    const params = new URLSearchParams({ limit: String(limit) });
    if (since) params.set('since', since);
    return await apiGet<Message[]>(`/my/messages/conversations/${encodeURIComponent(conversationId)}/messages?${params}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchThread failed');
  }
}

export async function searchMessages(
  query: string,
  opts: { conversationId?: string; limit?: number; mode?: SearchMode; since?: string; offset?: number } = {},
): Promise<MessageSearchResponse> {
  try {
    const params = new URLSearchParams({ q: query });
    if (opts.conversationId) params.set('conversationId', opts.conversationId);
    if (opts.limit !== undefined) params.set('limit', String(opts.limit));
    if (opts.mode) params.set('mode', opts.mode);
    if (opts.since) params.set('since', opts.since);
    if (opts.offset !== undefined && opts.offset > 0) params.set('offset', String(opts.offset));
    return await apiGet<MessageSearchResponse>(`/my/messages/search?${params}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('searchMessages failed');
  }
}
