import VisitRDandPD from "./VisitRD&PDModel.js";

const parseDate = (dateStr) => {
  const [day, month, year] = dateStr.split("/").map(Number);
  return new Date(Date.UTC(year, month - 1, day));
};

// Controller for creating a visit record
export const createVisit = async (req, res) => {
  try {
    const visitBy = req.user._id;
    const visitUserType = req.userType;
    const {
      addedFor,
      addedForId,
      tradename,
      visitDate,
      visitTime,
      meetingsummary,
      followup,
      visitpurpose,
      nextvisitdate,
    } = req.body;
    if (
      !addedFor ||
      !addedForId ||
      !tradename ||
      !visitDate ||
      !meetingsummary
    ) {
      return res.status(400).json({ message: "All fields are required" });
    }

    const parsedDate = parseDate(visitDate);
    const nextvisit = parseDate(nextvisitdate);
    let documents = [];
    if (req.files && req.files.documents) {
      const documentFiles = Array.isArray(req.files.documents)
        ? req.files.documents
        : [req.files.documents];
      for (const file of documentFiles) {
        const result = await cloudinary.v2.uploader.upload(file.tempFilePath, {
          folder: "chemiNova/visitdistributors",
        });

        documents.push({
          public_id: result.public_id,
          url: result.secure_url,
        });
      }
    }

    // Create a new visit record
    const newVisit = new VisitRDandPD({
      visitBy,
      visitUserType,
      addedFor,
      addedForId,
      tradename,
      visitDate: parsedDate,
      visitTime,
      visitpurpose,
      meetingsummary,
      followup,
      nextvisitdate: nextvisit,
      documents,
    });

    // Save the visit record to the database
    const savedVisit = await newVisit.save();

    return res
      .status(201)
      .json({ message: "Visit created successfully", visit: savedVisit });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: "Server error" });
  }
};

// Controller for fetching all visits for a specific distributor (RD or PD)
export const getVisitsByDistributor = async (req, res) => {
  try {
    const { distributorId, distributorType } = req.params;

    // Validate distributor type
    if (
      !["RetailDistributor", "PrincipalDistributor"].includes(distributorType)
    ) {
      return res.status(400).json({ message: "Invalid distributor type" });
    }

    // Find all visits for the specified distributor
    const visits = await VisitRDandPD.find({
      addedFor: distributorType,
      addedForId: distributorId,
    }).populate("visitBy", "name email"); // Populating visitBy with user details

    if (!visits.length) {
      return res
        .status(404)
        .json({ message: "No visits found for this distributor" });
    }

    return res.status(200).json({ visits });
  } catch (error) {
    console.error(error);
    return res.status(500).json({ message: "Server error" });
  }
};
