const Bot = require("../models/chatbot.model.js");
const { OpenAI } = require("openai");
const Tweets = require("../models/twitter.model.js");
const Token = require("../models/token.model.js");

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const CreateTweets = async (req, res) => {
  try {
    const { botuuid } = req.params;

    const token = await Token.findOne({ assignedBotUuid: botuuid });
    if (!token) {
      return res.status(404).json({ message: "Token not found" });
    }
    const bot = await Bot.findOne({ uuid:botuuid });
    if (!bot) {
      return res.status(404).json({ message: "Bot not found" });
    }

    const savedTweets = [];

    for (let i = 0; i < 5; i++) {
      const prompt = `Generate a creative, engaging, and concise tweet (under 280 characters) based on the following description: "${token.description}" and also use this infromation "${bot.trainingData}".`;

      const response = await openai.chat.completions.create({
        messages: [
          { role: "system", content: "You are a social media assistant." },
          { role: "user", content: prompt },
        ],
        model: "gpt-3.5-turbo",
        temperature: 0.7,
      });

      const tweetContent = response.choices[0].message.content.trim();

      const tweetDoc = await Tweets.create({
        botuuid,
        tokenDescription: token.description,
        tokenName: token.name,
        tweets: tweetContent,
      });

      savedTweets.push(tweetDoc);
    }

    res.status(201).json({
      message: "5 tweets created and stored separately",
      data: savedTweets,
    });
  } catch (error) {
    res
      .status(500)
      .json({ message: "Internal server error", error: error.message });
  }
};

const GetTweets = async (req, res) => {
  try {
    const { botuuid } = req.params;
    const user = req.user.id;
    const tweets = await Tweets.find({ botuuid, user });

    if (!tweets || tweets.length === 0) {
      return res
        .status(404)
        .json({ message: "No tweets found for this botuuid" });
    }

    res
      .status(200)
      .json({ message: "Tweets fetched successfully", data: tweets });
  } catch (error) {
    res
      .status(500)
      .json({ message: "Internal server error", error: error.message });
  }
};

module.exports = {
  CreateTweets,
  GetTweets,
};
