const { filterAndFormatPhones } = require("../helpers/common");
const Customers = require("../models/Customers");
const whispir = require("../helpers/whispir");

const priceUpdateText = async () => {
  try {
    const customers = await Customers.findAll({
      attributes: [
        "id",
        "first_name",
        "last_name",
        "phone",
        "phone_2",
        "phone_3",
        "hardware_name",
      ],
      raw: true,
    });

    const result = customers
      .map((customer) => {
        const formattedPhones = filterAndFormatPhones([
          customer.phone,
          customer.phone_2,
          customer.phone_3,
        ]);

        if (!formattedPhones || formattedPhones.length === 0) {
          return null;
        }

        const customerName =
          customer.hardware_name && customer.hardware_name.trim() !== ""
            ? customer.hardware_name
            : `${customer.first_name || ""} ${customer.last_name || ""}`.trim();

        return {
          customer_id: customer.id,
          customer_name: `${customer.first_name || ""} ${customer.last_name || ""}`.trim(),
          company_name: customerName,
          phone_number: formattedPhones.join(","),
        };
      })
      .filter(Boolean);

    console.log("Formatted resource payload:", result);

    if (result.length === 0) {
      console.log("No valid customers with phone numbers found.");
      return null;
    }

    const sample = [{
        customer_id: 1,
        customer_name: "Jimboy Reyes",
        company_name: "Jimboy Reyes",
        phone_number: "639217236957"
    }]
    const resources = await whispir.resource.createResource(result);

    console.log("Whispir resource response:", resources?.data);
    const resourceId = resources?.data?.id;
    console.log('Extracted resource ID:', resourceId);

    await whispir.messaging.bulkMessaging(
        { resourceId, mobile_mapping_field: "phone_number" },
        "194C0DC942A2194B",
        "Buildhub Ph SMS",
      );


    // return resources;
  } catch (err) {
    console.error("Error in priceUpdateText:", err);
    throw err;
  }
};

module.exports = {
  priceUpdateText,
};