import PropertyModal from "../models/property.js";
import UserModal from "../models/user.js";
import mongoose from "mongoose";
// import { v4 as uuidv4 } from "uuid";

export const createProperty = async (req, res) => {
    const propertyData = req.body;
    console.log('Property received:', propertyData);
    function generateRandomNumber() {
      return Math.floor(Math.random() * 90000) + 10000;
    }
    const randomNumber = generateRandomNumber().toString();
    const propertyId = `ELPI${randomNumber}`;

    const newProperty = new PropertyModal({
        ...propertyData,
        _id: new mongoose.Types.ObjectId(),  // Explicitly generating _id
        creator: req.userId,
        createdAt: new Date().toISOString(),
        publishedAt: new Date().toISOString(),
        currentYear: new Date().getFullYear(),
        propertyId: propertyId,
      });

      console.log('newProperty received:', newProperty);

      try {
        await newProperty.save();
       
        res.status(201).json(newProperty);
      } catch (error) {
        // Log the full error object to see what's inside
      console.log("Error fetching properties:", error);

      // Capture and return a meaningful error message
      if (error.response && error.response.data) {
        return rejectWithValue(error.response.data);
      } else {
        return rejectWithValue({ message: "Unknown error occurred" });
      }
      }
};

// Fetch property by userId.. Gets the specific user properties
export const getUserProperties = async (req, res) => {
  const { userId } = req.params;
  const { page = 1, limit = 10 } = req.query; // Defaults to page 1 and limit 10
  const skip = (page - 1) * limit;

  try {
    const properties = await PropertyModal.find({ userId: userId }) 
    .skip(skip)
    .limit(Number(limit));
    const total = await PropertyModal.countDocuments({ userId });
    const totalPages = Math.ceil(total / limit);

     res.json({
      properties,
      totalPages,
      currentPage: Number(page),
    });
  } catch (error) {
    res.status(500).json({ message: "Error retrieving properties", error });
  }
};


// Fetch property by ID.. which is property view page
export const getPropertyById = async (req, res) => {
  const { propertyId } = req.params;
  try {
    const property = await PropertyModal.findOne({ propertyId });
    res.status(200).json(property);
  } catch (error) {
    res.status(404).json({ message: "Something went wrong" });
  }
};

// Update property by ID.. 
export const updatePropertyById = async (req, res) => {
  const { id } = req.params; // This should be the propertyId
  const updateData = req.body;

  console.log("Received propertyId:", id); // Log the received propertyId
  console.log("updateData", updateData);

  try {
    // Find the property by propertyId instead of _id
    const updatedProperty = await PropertyModal.findOneAndUpdate(
      { propertyId: id }, // Search by propertyId
      updateData,
      { new: true }
    );

    if (!updatedProperty) {
      return res.status(404).json({ message: "Property not found" });
    }

    res.status(200).json(updatedProperty);
  } catch (error) {
    console.error("Error updating property:", error.message);
    res.status(500).json({ message: "Failed to update property", error: error.message });
  }
};

// export const getProperties = async (req, res) => {
//   try {
//     const properties = await PropertyModal.find(); // Fetch all properties from MongoDB
//     res.status(200).json(properties);
//   } catch (error) {
//     res.status(500).json({ message: "Server error" });
//   }
// };


// export const getProperties = async (req, res) => {
//   try {
//     const { page = 1, limit = 10 } = req.query;
//     const skip = (page - 1) * limit;
//     const totalProperties = await PropertyModal.countDocuments();
//     const properties = await PropertyModal.find()
//       .sort({ createdAt: -1 })
//       .skip(skip)
//       .limit(parseInt(limit));

//     res.status(200).json({
//       success: true,
//       data: properties,
//       totalPages: Math.ceil(totalProperties / limit),
//       currentPage: parseInt(page), // Include the currentPage in the response
//     });
//   } catch (err) {
//     res.status(500).json({ success: false, message: 'Server error' });
//   }
// };


export const getProperties = async (req, res) => {
  try {
    const { page = 1, limit = 10, keyword = "" } = req.query;
    const skip = (page - 1) * limit;

    // Use a filter to match the keyword if provided
    const keywordFilter = keyword 
      ? { address: { $regex: keyword, $options: "i" } } 
      : {};

    const totalProperties = await PropertyModal.countDocuments(keywordFilter);
    const properties = await PropertyModal.find(keywordFilter)
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));

    res.status(200).json({
      success: true,
      data: properties,
      totalPages: Math.ceil(totalProperties / limit),
      currentPage: parseInt(page),
    });
  } catch (err) {
    res.status(500).json({ success: false, message: 'Server error' });
  }
};




