const moment = require('moment')
const { empty } = require('../Helpers/Common')
const Chat = require('../models/clientChat')
const Client = require('../models/client')
const Admin = require('../models/admin')
const RequestActivity=require('../models/RequestActivity')
const Request = require('../models/request')
const loadNewMsg = async (req, reply) => {
    try {

        let { partnerId, userId, requestId } = req.body
        if (!empty(partnerId) && !empty(requestId)) {

        }
    }
    catch (error) {
        reply.status(500).send({ message: "Server error:" + error })
    }
}
const sendMessage = async (req, reply) => {
    try {
        let { userId, userType, requestId, to, msg,image,isVendor ,from_status} = req.body
        if (userType == 3) {
            let partner = await Client.getPartnerByUserId(userId);
            console.log("##############", partner);
            to = partner.id;

        }
        // let image = '';
        let data = {}
        data.request_id = requestId
        data.partner_id = to
        data.user_id = userId
        data.message = msg
        data.image = image
        data.from_status=from_status
        data.timestamp = moment().unix()
        console.log("$$$$$$$$$$$$$$$$$", data);
        if(!empty(image)){
           
                 if(isVendor!==1){
                  let approvedImage={}
                  approvedImage.name=image;
                  approvedImage.request_id=requestId;
                  approvedImage.design_order_id=requestId;
                  approvedImage.added_by=userId
                  approvedImage.approved = 0
                  approvedImage.isChat = 1        //for deisign order
                  approvedImage.timestamp=moment().unix()
                  let upload = await Request.addRequestAttachments(approvedImage)
                  data.image_id = upload

                  if(from_status == 1){
                    let result = await Request.getAllDesignOrders(requestId, 1, 1);
                    result = result.data
                    console.log('result', result)
                    approvedImage.isDesign = result[0]?.send_client_app_req == 1 ? 2 : 1
                    console.log('approvedImage', approvedImage)
                    let upload2 = await Request.addDesignOrderAttachments(approvedImage)
                    // data.image_id = upload2
                    console.log('upload2upload2',upload2)
                  }
                 }
                
                let notification_msg = `New Design  has been uploaded`
                let notification_url = `official-request/view/${requestId}`
            
                let adminIds = await Admin.getAllAdminIds();
                let clientUserIds = await Admin.getAllClientUserIds();
                let allUserIds = [...new Set([...adminIds, ...clientUserIds].filter(Boolean))];
                
                for (let eachUserId of allUserIds) {
                  if (eachUserId != userId) {
                    let incrementResult = await Admin.incrementField(eachUserId, 'noti_count', 1)
                    let addNotification = {
                      user_id: eachUserId,
                      url: notification_url,
                      timestamp: moment().unix(),
                      message: notification_msg,
                      status: 1,
                      from_id: userId,
                    }
                    const addNotificationResult = await Admin.addNotification(addNotification);
                  }
                }
                let requestActivity = {}
                requestActivity['request_id'] = requestId;
                requestActivity['activity'] = notification_msg;
                requestActivity['added_by'] = userId
                requestActivity['timestamp'] = moment().unix()
                let reqActivityId = await RequestActivity.addRequestUpdate(requestActivity)
               
            
              
        }
        let result = await Chat.setRequestMessage(data)
        if (!empty(result)) {

            let update = await Chat.updateLastSeen(requestId, userId, to)
            reply.send({ status: 1, message: "Message sent" });
        }
        else {
            reply.send({ status: 0, message: "Message sent failed" });
        }
    }
    catch (error) {
        console.log("##########Errorrrrrrrr",error);
        reply.status(500).send("Server error:", error)
    }
}
// const sendJobNoteMessage = async (req, reply) => {
//   try {
//     let { userId, userType, requestId, to, msg, image, isVendor, from_status } = req.body;

//     if (!Array.isArray(to)) {
//       to = [to];
//     }

//     if (userType == 3) {
//       const partner = await Client.getPartnerByUserId(userId);
//       to = [partner.id];
//     }

//     if (!to.length) {
//       return reply.send({ status: 0, message: "No recipients found" });
//     }

//     for (const recipientId of to) {
//       const data = {
//         request_id: requestId,
//         partner_id: recipientId,
//         user_id: userId,
//         message: msg,
//         image: image,
//         from_status: from_status,
//         timestamp: moment().unix()
//       };

//       await Chat.setJobNoteMessage(data);
//     }

//     reply.send({ status: 1, message: "Messages sent" });

//   } catch (error) {
//     console.error("Error sending job note messages:", error);
//     reply.status(500).send({ status: 0, message: "Server error" });
//   }
// };

const sendJobNoteMessage = async (req, reply) => {
  try {
    let { userId, userType, requestId, designOrderId, to, msg, image, isVendor, from_status, converted_design_request_id } = req.body;

    // Normalize `to` as array
    if (!Array.isArray(to)) {
      to = [to];
    }

    // For client: override `to` with their partner
    if (userType == 3) {
      const partner = await Client.getPartnerByUserId(userId);
      to = [partner.user_id];
    }

    if (!to.length) {
      return reply.send({ status: 0, message: "No recipients found" });
    }

    // ✅ Convert to comma-separated string
    const partnerIdsString = to.join(',');

    // Use converted_design_request_id if available, otherwise use requestId
    const finalRequestId = converted_design_request_id || requestId || null;

    const data = {
      request_id: finalRequestId,
      design_order_id: designOrderId || null,
      partner_id: partnerIdsString, // comma-separated
      user_id: userId,
      message: msg,
      image: image,
      from_status: from_status,
      timestamp: moment().unix()
    };

    await Chat.setJobNoteMessage(data);

    return reply.send({ status: 1, message: "Message sent" });

  } catch (error) {
    console.error("Error sending job note messages:", error);
    return reply.status(500).send({ status: 0, message: "Server error" });
  }
};


const viewMessage = async (req, reply) => {

    let { partnerId, userId, requestId, userType,from_status } = req.body
    if (userType == 3) {
        let partner = await Client.getPartnerByUserId(userId);
        console.log("##############", partner);
        partnerId = partner.id;

    }
    if (!empty(partnerId) && !empty(requestId)) {
        let messages = await Chat.getLastUserMsg(requestId, partnerId, userId,from_status)
        let update = await Chat.updateLastSeen(requestId, userId, partnerId)
        reply.send({ status: 1, message: messages });
    }
    else {
        reply.send({ status: 0, message: "Failed to fetch messages" });
    }
}

const viewJobNoteMessage = async (req, reply) => {

    let { partnerId, userId, requestId, designOrderId, userType,from_status } = req.body
    if (userType == 3) {
        let partner = await Client.getPartnerByUserId(userId);
        console.log("##############", partner);
        partnerId = partner.user_id;

    }
    if (((userType === 1 || userType === 8 || !empty(partnerId) || !empty(userId)) && (!empty(requestId) || !empty(designOrderId)))) {
        let messages = await Chat.getLastUserJobNoteMsg(requestId, partnerId, userId,userType,from_status, designOrderId)
        // let update = await Chat.updateLastSeen(requestId, userId, partnerId)
        reply.send({ status: 1, message: messages });
    }
    else {
        reply.send({ status: 0, message: "Failed to fetch messages" });
    }
}

const submitReview = async (req, reply) => {
    let review = {}
    let values = req.body.feedbackData
    console.log('$$$$$$$$$$$$$$$$$$$',values)
    review['partner_id'] = req.body.clientId
    review['quality_rating'] = values.qualityRating
    review['delivery_rating'] = values.deliveryRating
    review['value_for_money_rating'] = values.valueForMoneyRating
    review['review_comment'] = values.review
    review['recommended'] = values.recommended

    if (!empty(values.quest)) {
        let request = values.quest;
        review['request_id'] =request.map(item=>item.id).join(',');
    }
    if (!empty(values.services)) {
        let skills = values.services;
        review['skills'] = skills.map(item => item.id).join(',');

    }
    review['timestamp'] = moment().unix();
    review['added_by'] = req.body.userId;
    review['status'] = 1;
    let review_id = await Chat.addReview(review);
    console.log(review_id,'--------------------review_id')
    if (review_id) {
        let partner = await Client.getClientById(review_id.id)
        let notificationMsg = `Client  "${partner.name}" added a  review.`;
        let notificationUrl = "client";

        // Alert to user of new added project

        const incrementResult_User = await Admin.incrementField(req.body.userId, "noti_count", 1);
        console.log("incrementResult--to--user-----------", incrementResult_User)
        let notificationData_user = {
            user_id: req.body.userId,
            url: notificationUrl,
            timestamp: moment().unix(),
            message: notificationMsg,
            status: 1,
            from_id: req.body.userId,
        };

        const addNotificationResult_user = await Admin.addNotification(notificationData_user);

        // Alert to all admins of new added project

        let adminIds = await Admin.getAllAdminIds();
        let notificationData = {};

        for (const adminId of adminIds) {

            if (adminId != req.body.userId) {
                const incrementResult = await Admin.incrementField(adminId, "noti_count", 1);

                notificationData = {
                    user_id: req.body.userId,
                    url: notificationUrl,
                    timestamp: moment().unix(),
                    message: notificationMsg,
                    status: 1,
                    from_id: req.body.userId,
                };

                const addNotificationResult = await Admin.addNotification(notificationData);

            }
        }
        reply.send({ status: 1, message: "Review added Successfully" });
    }
    else{
        reply.send({ status: 0, message: "Failed to add  Review" });
    }
}

module.exports = { sendMessage, viewMessage, submitReview ,sendJobNoteMessage ,viewJobNoteMessage}