const Contact = require("../models/ContactModel");

// @desc    Create a new contact message
// @route   POST /api/contact
// @access  Public (Guests & Users)
exports.createContact = async (req, res) => {
  try {
    const { firstName, lastName, email, phone, message } = req.body;

    const newContact = await Contact.create({
      firstName,
      lastName,
      email,
      phone,
      message,
      status: "New", // Explicitly set to New, though default handles it
    });

    res.status(201).json({
      success: true,
      message: "Message sent successfully!",
      data: newContact,
    });
  } catch (error) {
    res.status(400).json({
      success: false,
      message: error.message,
    });
  }
};

// @desc    Get all contact messages
// @route   GET /api/contact
// @access  Private (Admin only)
exports.getAllContacts = async (req, res) => {
  try {
    // Sort by newest first
    const contacts = await Contact.find().sort({ createdAt: -1 });

    res.status(200).json({
      success: true,
      count: contacts.length,
      data: contacts,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};
exports.getContact = async (req, res) => {
  try {
    const contact = await Contact.findById(req.params.id);

    if (!contact) {
      return res
        .status(404)
        .json({ success: false, message: "Message not found" });
    }

    res.status(200).json({
      success: true,
      data: contact,
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "Server Error" });
  }
};
// @desc    Update contact status (e.g., mark as Read)
// @route   PATCH /api/contact/:id
// @access  Private (Admin only)
exports.updateContactStatus = async (req, res) => {
  try {
    const { status } = req.body;

    // Validate if status is one of the allowed enum values
    const allowedStatuses = ["New", "Read", "In Progress", "Resolved"];
    if (!allowedStatuses.includes(status)) {
      return res
        .status(400)
        .json({ success: false, message: "Invalid status" });
    }

    const contact = await Contact.findByIdAndUpdate(
      req.params.id,
      { status: status },
      { new: true, runValidators: true }
    );

    if (!contact) {
      return res
        .status(404)
        .json({ success: false, message: "Message not found" });
    }

    res.status(200).json({
      success: true,
      data: contact,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};

// ✅ NEW: Optimized Notification Endpoint
exports.getNotifications = async (req, res) => {
  try {
    // 1. Count all "New" messages (Very fast)
    const count = await Contact.countDocuments({ status: "New" });

    // 2. Get only the latest 5 "New" messages (Lightweight)
    const recent = await Contact.find({ status: "New" })
      .sort({ createdAt: -1 })
      .limit(5)
      .select("firstName lastName message createdAt"); // Select only needed fields

    res.status(200).json({
      success: true,
      data: {
        count,
        recent,
      },
    });
  } catch (error) {
    res.status(500).json({ success: false, message: "Server Error" });
  }
};
exports.deleteContact = async (req, res) => {
  try {
    const contact = await Contact.findByIdAndDelete(req.params.id);

    if (!contact) {
      return res
        .status(404)
        .json({ success: false, message: "Message not found" });
    }

    res.status(204).json({
      success: true,
      data: null,
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: "Server Error",
    });
  }
};
