const jwt = require("jsonwebtoken");
const Orders = require("../models/ordersModel");
const User = require("../models/userModel");
const Campaign = require("../models/campaignsModel");
const moment = require("moment/moment");
const Winners = require("../models/winnersModel");

const verification = async (token) => {
  try {
    // if (token.startsWith("Bearer ")) {
    //   TokenArray = token.split(" ");
    //   const decoded = jwt.verify(TokenArray[1], process.env.JWT_SECRET);
    //   const user = await User.findOne({ _id: decoded.id });
    //   if (user !== null && decoded.exp > Date.now() / 1000) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // } else {
    //   return false;
    // }
    return true;
  } catch (error) {
    return false;
  }
};

exports.getTicketsByCampaignId = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const campaignID = req.params.id;
    const ordersList = [];
    const orders = await Orders.find({ IsDelete: false });
    orders.map((order) => {
      const filtered = order.Items.filter(
        (item) => item.campaignId === campaignID
      );
      filtered.map((item) => {
        ordersList.push({
          // campaignId: item.campaignId,
          customerID: order.customerId,
          // productID: item.id,
          Tickets: item.Tickets * item.Quantity,
        });
      });
    });

    const mergedData = {};

    // Merge tickets based on ID
    ordersList.forEach((item) => {
      if (mergedData[item.customerID]) {
        mergedData[item.customerID] += item.Tickets;
      } else {
        mergedData[item.customerID] = item.Tickets;
      }
    });

    // Convert mergedData object back to array format
    const mergedArray = Object.keys(mergedData).map((customerID) => ({
      customerID,
      tickets: mergedData[customerID],
      campaignId: campaignID,
    }));

    const users = await User.find({ IsDelete: false });

    const finalData = mergedArray.map((item) => {
      const filtered = users.find((user) => user._id == item.customerID);

      return {
        ...item,
        customerName: filtered.firstName + " " + filtered.lastName,
      };
    });

    res.setHeader("Content-Type", "application/javascript");
    res.status(200).send({
      message: "",
      IsSuccess: true,
      Status_Code: 200,
      Data: finalData,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};

exports.declareWinner = async (req, res, next) => {
  const isVerified = await verification(req.headers["authorization"]);
  if (isVerified) {
    const body = req.body;

    const campaigns = await Campaign.findById(body.campaignId);

    const winners = await Winners.find({
      IsDelete: false,
      campaignId: body.campaignId,
    });

    if (winners.length > 0) {
      const updateWinner = await Winners.updateOne(
        { _id: winners[0]._id },
        {
          $set: {
            name: body.customerName,
            campaignId: body.campaignId,
            imageURL: campaigns ? campaigns.imageURL[0] : [],
            announcedOn: moment().format("YYYY-MMM-DDTHH:mm"),
            ModifiedBy: body.User,
            ModifiedOn: moment().format("YYYY-MMM-DD"),
          },
        }
      );
    } else {
      const data = {
        name: body.customerName,
        campaignId: body.campaignId,
        announcedOn: moment().format("YYYY-MMM-DDTHH:mm"),
        imageURL: campaigns ? campaigns.imageURL[0] : [],
        IsActive: true,
        IsDelete: false,
        CreatedBy: body.User,
        CreatedOn: moment().format("YYYY-MMM-DD"),
      };
      const newWinner = await Winners.create(data);
    }

    res.json({
      message: "Winner declared successfully.",
      IsSuccess: true,
      Status_Code: 200,
      Data: null,
    });
  } else {
    res.setHeader("Content-Type", "application/javascript");
    res.status(401).send({
      message: "Unauthorized access! Please Login again.",
      IsSuccess: false,
      Status_Code: 401,
      Data: null,
    });
  }
};
