const CHANNEL_URL = process.env.CHANNEL_URL || "http://127.0.0.1:7100";
const CHANNEL_SECRET = process.env.CHANNEL_SECRET || "";

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;
}

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

export 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>;
}

export 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>;
}

export 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[] }>;
}

export 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>;
}
