interface ChatResponse {
  data: {
    chat_id: string;
    ai_response: {
      shopifyRecommendation: {
        products: any[];
      };
      woocommerceRecommendations: any | null;
      chatresponseanswer: string;
      humanAgent: any[];
    };
  };
}

interface SendMessageParams {
  message: string;
  chatId?: string;
  agentId: string;
  secretKey: string;
  userName: string;
}

/**
 * Send a message to the chat API
 * First call will initialize chat and return chat_id
 * Subsequent calls should include the chat_id
 */
export async function sendChatMessage({
  message,
  chatId,
  agentId,
  secretKey,
  userName,
}: SendMessageParams): Promise<ChatResponse> {
  try {
    const body: any = {
      text: message,
      agent_id: agentId,
      secret_key: secretKey,
      user_name: userName,
    };

    // Include chat_id for subsequent messages
    if (chatId) {
      body.chat_id = chatId;
    }

    const response = await fetch("https://dev.agent.api.qixs.ai/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      throw new Error(`Chat API error: ${response.status} ${response.statusText}`);
    }

    const data: ChatResponse = await response.json();
    return data;
  } catch (error) {
    console.error("Error sending chat message:", error);
    throw error;
  }
}
