import Contact from "../models/Contact.js";

// Submit contact query
export const submitContact = async (req, res) => {
  try {
    const { userId, name, email, message } = req.body;

    if (!userId || !name || !email || !message) {
      return res.status(400).json({ message: "All fields are required" });
    }

    const contact = await Contact.create({ userId, name, email, message });
    res.status(201).json({ message: "Query submitted successfully", contact });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
};

// Get all queries (Admin)
export const getAllContacts = async (req, res) => {
  try {
    const contacts = await Contact.find().sort({ createdAt: -1 });
    res.status(200).json(contacts);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
};

// Get user queries by ID
export const getUserContacts = async (req, res) => {
  try {
    const { userId } = req.params;
    const contacts = await Contact.find({ userId }).sort({ createdAt: -1 });
    res.status(200).json(contacts);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
};

// Update status (Admin)
export const updateContactStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

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

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

    res.status(200).json({ message: "Status updated", contact });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
};
