import { Sales } from "./SalesModel.js";
import User from "../user/userModel.js";
import { KYC } from "../KYC/KycModel.js";
import ShippingAddress from "../ShippingAddresses/ShippingAddressModel.js";
import TerritoryManager from "../TerritoryManagers/TerritoryManagerModel.js";
import SalesCoordinator from "../SalesCoOrdinators/SalesCoOrdinatorModel.js";
import crypto from "crypto";
// Add Sales data
const parseDate = (dateStr) => {
  const [day, month, year] = dateStr.split("/").map(Number);
  // Create a UTC date object to ensure the correct date is stored
  return new Date(Date.UTC(year, month - 1, day));
};
export const addSales = async (req, res) => {
  try {
    const { products, addedFor, addedForId, tradename, date } = req.body;
    const userId = req.user._id;
    const userType = req.userType;
    // console.log("req.user", req.user);
    const currentYear = new Date().getFullYear().toString().slice(-2);
    const randomChars = crypto.randomBytes(4).toString("hex").toUpperCase();
    const uniqueId = `${currentYear}-${randomChars}`;
    // console.log("uniqueId", uniqueId);
   // Convert the date from DD/MM/YYYY string to Date object
   const parsedDate = parseDate(date);
    const newSales = new Sales({
      userId,
      userType,
      addedFor,
      addedForId,
      products,
      uniqueId,
      tradename,
      date: parsedDate,
    });
    // console.log("newSales", newSales);
    await newSales.save();
    res.status(201).json({
      success: true,
      message: "Sales added successfully",
      data: newSales,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "Server error", error });
  }
};

export const getAllSales = async (req, res) => {
  try {
    const { page = 1, show = 10, startDate, endDate, name } = req.query;
    const query = {};

    if (startDate && endDate) {
      const start = new Date(startDate);
      const end = new Date(endDate);

      if (start.toDateString() === end.toDateString()) {
        query.createdAt = {
          $gte: start,
          $lt: new Date(start).setDate(start.getDate() + 1),
        };
      } else {
        query.createdAt = {
          $gte: start,
          $lte: new Date(end).setDate(end.getDate() + 1),
        };
      }
    } else if (startDate && endDate === "") {
      query.createdAt = {
        $gte: new Date(startDate),
        $lte: new Date(),
      };
    } else if (endDate && startDate === "") {
      query.createdAt = {
        $lte: new Date(endDate),
      };
    }

    const allSales = await Sales.find(query).sort({ createdAt: -1 });

    // Populate additional details
    const populatedSales = await Promise.all(
      allSales.map(async (Sales) => {
        let user = null;
        if (Sales.userType === "TerritoryManager") {
          user = await TerritoryManager.findById(Sales.userId);
        } else if (Sales.userType === "SalesCoordinator") {
          user = await SalesCoordinator.findById(Sales.userId);
        }

        let addedForData = null;
        let tradeName = null;

        if (Sales.addedFor === "PrincipalDistributor") {
          addedForData = await User.findById(Sales.addedForId);
          if (addedForData) {
            const shippingAddress = await ShippingAddress.findOne({
              user: addedForData._id,
            });
            addedForData = {
              ...addedForData.toObject(),
              shippingAddress,
            };
            tradeName =
              addedForData.shippingAddress?.tradeName?.toLowerCase() || "";
          }
        } else if (Sales.addedFor === "RetailDistributor") {
          addedForData = await KYC.findById(Sales.addedForId);
          tradeName = addedForData?.trade_name?.toLowerCase() || "";
        }

        return {
          ...Sales.toObject(),
          user,
          addedForData,
          tradeName,
        };
      })
    );

    // Apply name filter if the name parameter is provided
    let filteredSales = populatedSales;
    if (name) {
      filteredSales = filteredSales.filter(
        (Sales) =>
          Sales.tradeName && Sales.tradeName.includes(name.toLowerCase())
      );
    }

    // Calculate total count of filtered data
    const total_data = filteredSales.length;

    // Apply pagination after filtering
    const paginatedSales = filteredSales.slice((page - 1) * show, page * show);

    // Calculate total pages
    const total_pages = Math.ceil(total_data / show);

    // Send response with pagination info
    res.status(200).json({
      total_data,
      total_pages,
      current_page: Number(page),
      Sales: paginatedSales,
    });
  } catch (error) {
    console.error("Error in getAllSales:", error);
    res.status(500).json({ message: error.message });
  }
};

// Get single Sales
export const getSingleSales = async (req, res) => {
  try {
    const { id } = req.params;

    const Sales = await Sales.findById(id);
    if (!Sales) {
      return res.status(404).json({ message: "Sales not found" });
    }

    // Populate user details based on userType
    let user = null;
    if (Sales.userType === "TerritoryManager") {
      user = await TerritoryManager.findById(Sales.userId);
    } else if (Sales.userType === "SalesCoOrdinator") {
      user = await SalesCoordinator.findById(Sales.userId);
    }

    // Populate addedFor details based on addedFor
    let addedForData = null;
    if (Sales.addedFor === "PrincipalDistributor") {
      addedForData = await User.findById(Sales.addedForId);
      const shippingAddress = await ShippingAddress.findOne({
        user: addedForData._id,
      });
      addedForData = {
        ...addedForData.toObject(),
        shippingAddress,
      };
    } else if (Sales.addedFor === "RetailDistributor") {
      addedForData = await KYC.findById(Sales.addedForId);
    }

    res.status(200).json({
      ...Sales.toObject(),
      user,
      addedForData,
    });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
};
