import axios from "axios";
import crypto from "react-native-quick-crypto";

class CPMChatAPI {
  constructor(baseUrl, clientId, clientSecret) {
    this.baseUrl = baseUrl;
    this.clientId = clientId;
    this.clientSecret = clientSecret;
  }

  generateSignature(timestamp, requestBody) {
    const data = this.clientId + timestamp + requestBody;
    
    // Using react-native-quick-crypto's createHmac
    const hmac = crypto.createHmac('sha256', this.clientSecret);
    hmac.update(data);
    return hmac.digest('hex');
  }

  async getHeaders(requestBody) {
    const timestamp = Date.now().toString();
    const signature = this.generateSignature(timestamp, requestBody);

    return {
      "Content-Type": "application/json",
      "X-Client-Id": this.clientId,
      "X-Timestamp": timestamp,
      "X-Signature": signature,
    };
  }


async initChat(userId, userName) {
    const requestBody = JSON.stringify({ userId, userName });
    const headers = await this.getHeaders(requestBody);

    try {
      const response = await axios.post(
        `${this.baseUrl}/chat/init`,
        { userId, userName },
        { headers }
      );
      return response.data;
    } catch (error) {
      throw new Error(
        `Init chat failed: ${error.response?.data?.message || error.message}`
      );
    }
  }


async sendMessage(userId, sessionId, query) {
    const requestBody = JSON.stringify({ userId, sessionId, query });
    const headers = await this.getHeaders(requestBody);

    try {
      const response = await axios.post(
        `${this.baseUrl}/chat/messages`,
        { userId, sessionId, query },
        { headers }
      );
      return response.data;
    } catch (error) {
      throw new Error(
        `Send message failed: ${error.response?.data?.message || error.message}`
      );
    }
  }


async endSession(userId, sessionId) {
    const requestBody = JSON.stringify({ userId, sessionId });
    const headers = await this.getHeaders(requestBody);

    try {
      const response = await axios.post(
        `${this.baseUrl}/chat/end-session`,
        { userId, sessionId },
        { headers }
      );
      return response.data;
    } catch (error) {
      throw new Error(
        `End session failed: ${error.response?.data?.message || error.message}`
      );
    }
  }
}

export default CPMChatAPI;