import { whatsappLog } from "../../serviceLog";
import moment from "moment";
import whatsappLedgerDB from "../model/ledger.model";
import whatsappPendingMessagesDB from "../../../models/whatsappPendingMessages.model";
import CONSTANTS from "../../../config/constants";
import axios from "axios";

// const args = process.argv.slice(2);
// const clientId = args[0] ? Number(args[0]) : 93;
// const mobile = args[1] || '9810511842';
// const rentDate = args[2] || moment().format("YYYY-MM-DD");

// console.log(`[rentDueSummaryMessage.ts], clientId [${clientId}], mobile [${mobile}], rentDate [${rentDate}]`);

const sendRentDueSummaryMessageToClient = async () => {
    const F = 'sendRentDueSummaryMessageToClient';
  try {
    // const mobile = '9810511842';
    const todayRentDues = await whatsappLedgerDB.getRentDueByClientIdAndDate({
        clientId: 801,
        rentDate: moment().format('YYYY-MM-DD')
    });

    let payload = ``;
    let tenantData = ``;
    let totalTenants = 0;
    let totalRentDue = 0;
    //Prime stay numbers below
    let mobile = '9373817173';
    let mobile2 = '9922073333';
    let rentDate = moment().format('YYYY-MM-DD');

    if (todayRentDues && todayRentDues.length > 0) {
        // for (let due of todayRentDues) {
        //     // tenantData += `${due.tenantName} (${due.tenantMobile}) - ₹${due.amount}, `;
        //     // totalTenants += 1;
        //     // totalRentDue += Number(due.amount);

        // }
        tenantData = todayRentDues.map((due: any) => {
            totalTenants += 1;
            totalRentDue += Number(due.amount);
            return `${due.tenantName} (${due.tenantMobile} - ${due.propName}) - ₹${due.amount}`;
        }).join(', ');
        console.log(`tenantData [${JSON.stringify(tenantData)}]`);
    
        // const body = {
        //   countryCode: "+91",
        //   userId: mobile,
        //   phoneNumber: mobile,
        //   traits: {
        //     name: "Prime Stay",
        //     email: "",
        //   },
        //   tags: ["sample-tag-1", "sample-tag-2"],
        // };
    
        // const response: any = await axios.post(
        //   `${process.env.WHATSAPP_ADD_USER_URI}`,
        //   body,
        //   {
        //     headers: {
        //       "Content-Type": "application/json",
        //       Authorization: process.env.WHATSAPP_API_KEY,
        //     },
        //   }
        // );
    
        // if (response?.data?.result) {
        //   console.log(
        //     `[${F}], Mobile [${mobile}], User Added successfully, Response : ${JSON.stringify(
        //       response?.data
        //     )}`
        //   );
        // } else {
        //   console.log(
        //     `[${F}], Mobile [${mobile}], Unable to add user, Response : ${JSON.stringify(
        //       response?.data
        //     )}`
        //   );
        //   return false;
        // }
    
        const messageBody = {
          countryCode: "+91",
          userId: mobile,
          phoneNumber: mobile,
          callbackData: "some text here",
          type: "Template",
          template: {
            name: "today_rent_due_summary",
            languageCode: "en",
            bodyValues: [moment(rentDate).format("DD-MM-YYYY"), tenantData, totalTenants, `₹${totalRentDue}`],
          },
        };
    
        const response2: any = await axios.post(
          `${process.env.WHATSAPP_SEND_MESSAGE_URI}`,
          messageBody,
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: process.env.WHATSAPP_API_KEY,
            },
          }
        );
    
        if (response2?.data?.result) {
          console.log(
            `[${F}], Mobile [${mobile}], Message sent successfully, Response : ${JSON.stringify(
              response2?.data
            )}`
          );
        } else {
          console.log(
            `[${F}], Mobile [${mobile}], Unable to send message, Response : ${JSON.stringify(
              response2?.data
            )}`
          );
        }

        const messageBody2 = {
          countryCode: "+91",
          userId: mobile2,
          phoneNumber: mobile2,
          callbackData: "some text here",
          type: "Template",
          template: {
            name: "today_rent_due_summary",
            languageCode: "en",
            bodyValues: [moment(rentDate).format("DD-MM-YYYY"), tenantData, totalTenants, `₹${totalRentDue}`],
          },
        };
    
        const response3: any = await axios.post(
          `${process.env.WHATSAPP_SEND_MESSAGE_URI}`,
          messageBody2,
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: process.env.WHATSAPP_API_KEY,
            },
          }
        );
    
        if (response3?.data?.result) {
          console.log(
            `[${F}], Mobile [${mobile2}], Message sent successfully, Response : ${JSON.stringify(
              response3?.data
            )}`
          );
        } else {
          console.log(
            `[${F}], Mobile [${mobile2}], Unable to send message, Response : ${JSON.stringify(
              response3?.data
            )}`
          );
        }
    }


    process.exit(0);
  } catch (error: any) {
    console.log(
      `[${F}], Error: ${
        JSON.stringify(error?.response?.data) || error?.message || error
      }`,
    );

    process.exit(0);
  }
};

sendRentDueSummaryMessageToClient();