interface SendMessageResult {
  conversation_id: string;
  message_id: string;
}

interface Conversation {
  id: string;
  messages: ChatMessage[];
  created_at: number;
  updated_at: number;
}

interface ChatMessage {
  id: string;
  role: "user" | "assistant";
  text: string;
  timestamp: number;
  user_email?: string;
}

interface HealthStatus {
  status: string;
  uptime: number;
}

export function createChannelClient(channelUrl: string, channelSecret: string) {
  async function channelFetch(
    path: string,
    options: RequestInit = {}
  ): Promise<Response> {
    return fetch(`${channelUrl}${path}`, {
      ...options,
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${channelSecret}`,
        ...options.headers,
      },
    });
  }

  async function sendMessage(
    text: string,
    userEmail: string,
    conversationId?: string
  ): Promise<SendMessageResult> {
    const res = await channelFetch("/message", {
      method: "POST",
      body: JSON.stringify({
        text,
        conversation_id: conversationId,
        user_email: userEmail,
      }),
    });

    if (!res.ok) {
      throw new Error(`Channel server error: ${res.status}`);
    }

    return res.json() as Promise<SendMessageResult>;
  }

  async function getConversation(
    conversationId: string
  ): Promise<Conversation> {
    const res = await channelFetch(`/conversations/${conversationId}`);
    if (!res.ok) {
      throw new Error(`Channel server error: ${res.status}`);
    }
    return res.json() as Promise<Conversation>;
  }

  async function listConversations(): Promise<{
    conversations: Conversation[];
  }> {
    const res = await channelFetch("/conversations");
    if (!res.ok) {
      throw new Error(`Channel server error: ${res.status}`);
    }
    return res.json() as Promise<{ conversations: Conversation[] }>;
  }

  async function getHealth(): Promise<HealthStatus> {
    const res = await channelFetch("/health");
    if (!res.ok) {
      throw new Error(`Channel server error: ${res.status}`);
    }
    return res.json() as Promise<HealthStatus>;
  }

  return { sendMessage, getConversation, listConversations, getHealth };
}
