const { Op, Sequelize } = require("sequelize");
const Customers = require("../models/Customers");
const OrderForm = require("../models/OrderForm");
const { filterAndFormatPhones } = require("../helpers/common");
const whispir = require("../helpers/whispir");
const MessagesLogs = require("../models/MessagesLogs");
const InactiveCustomerTextMsgHistory = require("../models/InactiveCustomerTextMsgHistory");
const AutomationServicesLogs = require("../models/AutomationServicesLogs");
const schedule = require("node-schedule");

async function inactiveCustomers() {
  try {
    const thirtyDaysAgo = new Date();
    thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

    const inactiveCustomers = await Customers.findAll({
      include: [
        {
          model: OrderForm,
          as: "order_form_details",
          attributes: [],
          where: {
            date_created: {
              [Op.gte]: thirtyDaysAgo,
            },
          },
          required: false,
        },
      ],
      where: Sequelize.literal(`
              customers.id NOT IN (
                  SELECT customer_id FROM order_form 
                  WHERE date_created >= '${thirtyDaysAgo.toISOString()}'
                  GROUP BY customer_id
              )
          `),
    });

    const inactiveCustomerIds = inactiveCustomers.map((customer) => customer.id);
    const recentlyTextedCustomers = await InactiveCustomerTextMsgHistory.findAll({
      attributes: ["customer_id"],
      where: {
        customer_id: {
          [Op.in]: inactiveCustomerIds,
        },
        last_date_text: {
          [Op.gte]: thirtyDaysAgo,
        },
      },
    });
    const recentlyTextedCustomerIds = recentlyTextedCustomers.map((textMsg) => textMsg.customer_id);

    const finalInactiveCustomers = inactiveCustomers.filter(
      (customer) => !recentlyTextedCustomerIds.includes(customer.id)
    );
    const receiverPhoneNumbers = finalInactiveCustomers.map((customer) => filterAndFormatPhones([customer?.phone]));
    const result = finalInactiveCustomers.map((customer) => ({
      customer_id: customer.id,
      customer_name: `${customer.first_name} ${customer.last_name}`,
      company_name: customer.hardware_name,
      phone_number: filterAndFormatPhones([customer?.phone]).join(","),
    }));

    const resources = await whispir.resource.createResource(result);

    const inactiveCustomerTextMsgHistoryLogData = result.map((res) => ({
      customer_id: res.customer_id,
      phone: res.phone_number,
      last_date_text: new Date(),
    }));

    let bulkMessage = null;
    if (resources) {
      const resourceId = resources?.data?.id;
      bulkMessage = await whispir.messaging.bulkMessaging(
        { resourceId, mobile_mapping_field: "phone_number" },
        "E3F3700892383C2D",
        "Buildhub Ph SMS"
      );

      await InactiveCustomerTextMsgHistory.bulkCreate(inactiveCustomerTextMsgHistoryLogData);
    }
    await MessagesLogs.create({
      customer_id: 0,
      type: "Bulk Message",
      receiver: receiverPhoneNumbers.join(","),
      content: "Inactive Customers Text",
      is_sent: bulkMessage ? true : false,
    });

    await AutomationServicesLogs.create({
      automation_type: "Inactive Customers",
      is_success: bulkMessage ? true : false,
    });
  } catch (err) {
    throw err;
  }
}

const inactiveCustomersJob = schedule.scheduleJob("0 10 * * *", async () => {
  const currentHour = new Date().getHours();
  const currentMinutes = new Date().getMinutes();
  if (currentHour === 10 && currentMinutes === 0) {
    await inactiveCustomers();
  }
});

module.exports = inactiveCustomersJob;
