const WithYieldPromise = require("./withyield-loader");

class YieldClient {
  constructor(apiKey) {
    if (!apiKey) {
      throw new Error("API key is required");
    }
    this.client = null;
    this.apiKey = apiKey;
    this.sdkPromise = WithYieldPromise;
  }

  async initialize() {
    const WithYield = await this.sdkPromise;
    this.client = await WithYield.Client.create(this.apiKey);
    return this;
  }

  async findCustomerByCode(params) {
    if (!this.client) {
      throw new Error("Client not initialized. Call initialize() first.");
    }

    try {
      const customers = await this.client.customer.list(params);
      return customers;
    } catch (err) {
      console.error("Error finding customer:", err);
      throw err;
    }
  }

  async selfModule() {
    if (!this.client) {
      throw new Error("Client not initialized. Call initialize() first.");
    }

    try {
      const info = await this.client.self.info();
      console.log(info);
      return info;
    } catch (err) {
      console.error("Self Module: ", err);
      throw err;
    }
  }

  async createOrder(params) {
    if (!this.client) {
      throw new Error("Client not initialized. Call initialize() first.");
    }

    try {
      const info = await this.client.order.create(params);
      return info;
    } catch (err) {
      console.error("Self Module: ", err);
      throw err;
    }
  }

  async fetchOrder(params) {
    if (!this.client) {
      throw new Error("Client not initialized. Call initialize() first.");
    }

    try {
      const info = await this.client.order.fetch(params);
      return info;
    } catch (err) {
      console.error("Self Module: ", err);
      throw err;
    }
  }
}

let yieldClientInstance = null;

async function getYieldClient() {
  if (!yieldClientInstance) {
    const sandboxApiKey =
      "sb_api_80w54zbmg51496xk60ygev7x50$BO-1youXAE44EATodyO07rki6gLNwttItajU0QT0Vlk$kQ1e8RuPXxWgyFCwL7lI7yFa8JvDiLgXbhI-5_NJCos";
    const productApiKey =
      "api_3gmfxmpzgs6ts6xtqrzarnkjb4:RGdKKm-VciGYHEDLc_jFlbJSGoJZx2hw3AYky8Mp5XM:4vNjdc32FZYHJxSHHFWZrZyKEkWYeboo16qiMTDwwIo";
    yieldClientInstance = await new YieldClient(productApiKey).initialize();
  }
  return yieldClientInstance;
}

module.exports = getYieldClient;
