import { imageUrlToBase64, isBlobUrl } from "@/features/app";
import axios from "@/lib/axios";

class MessageApiService {
  async sendSingleMessage(message: IMessage) {
    try {
      const { data } = await axios.post("/messages", message);
      console.log("[NestJS] Response (single):", data);
      return data;
    } catch (err) {
      console.error("[NestJS] Error (single):", err);
      throw err;
    }
  }

  async sendBulkMessages(messages: IMessage[]) {
    try {
      const { data } = await axios.post("/messages/bulk", {
        data: messages,
      });
      console.log("[NestJS] Response (bulk):", data);
      return data;
    } catch (err) {
      console.error("[NestJS] Error (bulk):", err);
      throw err;
    }
  }

  async createAndSendToZulip(messages: IMessage[]) {
    try {
      const processedMessages = await Promise.all(
        messages.map(async (msg) => {
          // Nếu message là mảng
          if (Array.isArray(msg.message)) {
            const processedArray = await Promise.all(
              msg.message.map(async (item) => {
                if (isBlobUrl(item)) {
                  const base64 = await imageUrlToBase64(item);
                  return base64;
                }
                return item;
              })
            );

            return {
              ...msg,
              message: processedArray,
            };
          }

          // Nếu message là string
          if (isBlobUrl(msg.message || "")) {
            console.log("Found blob URL, converting to Base64:", msg.message);
            const base64 = await imageUrlToBase64(msg.message || "");
            return {
              ...msg,
              message: base64,
            };
          }

          return msg;
        })
      );

      const { data } = await axios.post("/messages/create-and-send", {
        data: processedMessages,
      });

      console.log("[NestJS] Response (create and send):", data);
      return data;
    } catch (err) {
      console.error("[NestJS] Error (create and send):", err);
      throw err;
    }
  }

  async sendLog(log: ILog) {
    try {
      const { data } = await axios.post("/messages/logs", log);
      console.log("[NestJS] Response (logs):", data);
      return data;
    } catch (err) {
      console.error("[NestJS] Error (logs):", err);
      throw err;
    }
  }
}

export const messageApi = new MessageApiService();
