const Thread = require("../models/thread.bot.model.js");

// Create a new thread
const createThread = async (req, res) => {
  try {
    const userId = req.user.userId;

    const { uuid } = req.params;

    if (!uuid) {
      return res.status(400).json({ message: "UUID is required" });
    }

    const thread = await Thread.create({
      uuid,
      user: userId,
    });

    res.status(201).json(thread);
  } catch (err) {
    res.status(500).json({
      message: "Failed to create thread",
      error: err.message,
    });
  }
};

// Get all threads
const getAllThreads = async (req, res) => {
  try {
    const threads = await Thread.find().populate("user", "username email");
    res.status(200).json(threads);
  } catch (err) {
    res
      .status(500)
      .json({ message: "Failed to fetch threads", error: err.message });
  }
};
const getUserThreads = async (req, res) => {
  try {
    const threads = await Thread.find({ user: req.user.id }).populate(
      "user",
      "username email"
    );
    res.status(200).json(threads);
  } catch (err) {
    res
      .status(500)
      .json({ message: "Failed to fetch user's threads", error: err.message });
  }
};
const UserThreadUuid = async (req, res) => {
  try {
    const { uuid } = req.params; // ✅ Extract just the uuid string
    const userId = req.user.userId;

    const threads = await Thread.find({ user: userId, uuid }).populate(
      "user",
      "username email"
    );

    res.status(200).json(threads);
  } catch (err) {
    res.status(500).json({
      message: "Failed to fetch user's threads",
      error: err.message,
    });
  }
};

// Delete a thread by ID
const deleteThread = async (req, res) => {
  try {
    const thread = await Thread.findByIdAndDelete(req.params.id);
    if (!thread) return res.status(404).json({ message: "Thread not found" });

    res.status(200).json({ message: "Thread deleted successfully" });
  } catch (err) {
    res
      .status(500)
      .json({ message: "Failed to delete thread", error: err.message });
  }
};

module.exports = {
  getUserThreads,
  createThread,
  getAllThreads,
  deleteThread,
  UserThreadUuid,
};
