const OrderForm = require("../models/OrderForm");
const Customers = require("../models/Customers");
const errorHandler = require("../util/errorHandler");
const Rpaf = require("../models/Rpaf");
const { where } = require("sequelize");

exports.createCustomer = (req, res, next) => {
  const {
    customerType,
    agentCode,
    agentName,
    hardwareName,
    firstName,
    lastName,
    email,
    password,
    phone,
    address,
    longitude,
    latitude,
    status,
  } = req.body;

  Customers.create({
    type: customerType,
    agent_code: agentCode,
    agent: agentName,
    hardware_name: hardwareName,
    first_name: firstName,
    last_name: lastName,
    email: email,
    password: password,
    phone: phone,
    address: address,
    longitude: longitude,
    latitude: latitude,
    status: status,
  })
    .then(() => {
      res.status(201).json({ success: true });
    })
    .catch((err) => {
      next(err);
    });
};

exports.updateCustomer = (req, res, next) => {
  const { customerId, impersonation } = req;
  const {
    customerType,
    agentCode = "",
    agentName,
    hardwareName,
    firstName,
    lastName,
    email,
    // password,
    phone,
    address,
    longitude,
    latitude,
    status,
  } = req.body;

  Customers.findOne({
    where: {
      id: customerId,
    },
  })
    .then((customer) => {
      if (!customer) {
        return errorHandler("Customer ID does not exist!", 404);
      }

      if (impersonation) {
        customer.address = address;
        customer.longitude = longitude;
        customer.latitude = latitude;
      } else {
        customer.type = customerType;
        if (agentCode !== "" && agentCode !== null) {
          customer.agent_code = agentCode;
        }
        customer.agent = agentName;
        customer.hardware_name = hardwareName;
        customer.first_name = firstName;
        customer.last_name = lastName;
        customer.email = email;
        customer.phone = phone;
        customer.address = address;
        customer.longitude = longitude;
        customer.latitude = latitude;
        customer.status = status;
      }

      return customer.save();
    })
    .then((updatedCustomer) => {
      // Get the total amount for orders associated with the customer
      // OrderForm.sum('total_amount', { where: { customer_id: customerId }})
      //     .then((totalAmount) => {
      //         if (totalAmount === null) {
      //             totalAmount = 0;
      //         }
      //         // Construct the response object with updated customer and totalAmount
      //         const response = {
      //             success: true,
      //             customer: {...updatedCustomer.dataValues, total_purchased: totalAmount},
      //             // totalAmountPurchased: totalAmount
      //         };
      //         // Send the response
      //         res.status(200).json(response);
      //     })
      //     .catch((err) => {
      //         next(err);
      //     });

      // Construct the response object with updated customer and totalAmount
      const { password, ...customerData } = updatedCustomer.dataValues;
      const response = {
        success: true,
        customer: customerData,
        // totalAmountPurchased: totalAmount
      };

      // Send the response
      res.status(200).json(response);
    })
    .catch((err) => {
      next(err);
    });
};

exports.deleteCustomer = (req, res, next) => {
  const { customerId } = req;

  Customers.findOne({
    where: {
      id: customerId,
    },
  })
    .then((customer) => {
      if (!customer) {
        return errorHandler("Customer ID does not exists!", 404);
      }
      return customer.destroy();
    })
    .then(() => {
      res.status(204).send();
    })
    .catch((err) => {
      next(err);
    });
};

exports.findCustomerById = (req, res, next) => {
  const { customerId } = req;

  Customers.findOne({
    where: {
      id: customerId,
    },
  })
    .then((customer) => {
      if (!customer) {
        return errorHandler("Customer ID does not exist!", 404);
      }

      OrderForm.sum("total_amount", { where: { customer_id: customerId } })
        .then((totalAmount) => {
          if (totalAmount === null) {
            totalAmount = 0;
          }
          // res.status(200).json({ success: true, customer, totalAmount });
          const { password, ...customerData } = customer.dataValues;
          return { ...customerData, total_purchased: totalAmount };
        })
        .then(async (customer) => {
          const rpaf = await Rpaf.findOne({
            where: {
              customer_id: 345,
            },
          });

          res.status(200).json({ success: true, customer: { ...customer, currentBalance: rpaf.current_bal ?? 0 } });
        })
        .catch((err) => {
          next(err);
        });
    })
    .catch((err) => {
      next(err);
    });
};

exports.findAllCustomer = (req, res, next) => {
  Customers.findAll({
    where: {
      type: "Buyer",
    },
  })
    .then((customers) => {
      // Array to store promises for calculating totalAmount for each customer
      const totalAmountPromises = customers.map((customer) => {
        // Calculate total amount for each customer
        return OrderForm.sum("total_amount", { where: { customer_id: customer.id } }).then((totalAmount) => {
          // Return an object with customer details and totalAmount
          return {
            id: customer.id,
            customerType: customer.type,
            agentCode: customer.agent_code,
            agentName: customer.agentName,
            hardwareName: customer.hardware_name,
            firstName: customer.first_name,
            lastName: customer.last_name,
            email: customer.email,
            // password: customer.password,
            phone: customer.phone,
            address: customer.address,
            longitude: customer.longitude,
            latitude: customer.latitude,
            status: customer.status,
            totalAmount: totalAmount || 0, // If totalAmount is null, default to 0
          };
        });
      });

      // Resolve all promises
      Promise.all(totalAmountPromises)
        .then((customerDetails) => {
          res.status(200).json({ success: true, customers: customerDetails });
        })
        .catch((err) => {
          next(err);
        });
    })
    .catch((err) => {
      next(err);
    });
};
