Subversion Repositories SmartDukaan

Rev

Rev 35969 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.web.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.spice.profitmandi.common.model.ProfitMandiConstants;
import com.spice.profitmandi.common.model.UserInfo;
import com.spice.profitmandi.common.web.util.ResponseSender;
import com.spice.profitmandi.dao.entity.auth.AuthUser;
import com.spice.profitmandi.dao.entity.dtr.User;
import com.spice.profitmandi.dao.enumuration.cs.EscalationType;
import com.spice.profitmandi.dao.repository.auth.AuthRepository;
import com.spice.profitmandi.dao.entity.dtr.Retailer;
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
import com.spice.profitmandi.dao.entity.cs.CallbackRequestReply;
import com.spice.profitmandi.dao.repository.cs.CallbackRequestReplyRepository;
import com.spice.profitmandi.dao.repository.cs.CallbackRequestRepository;
import com.spice.profitmandi.dao.repository.cs.CsService;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
import com.spice.profitmandi.web.req.CallbackReplyRequest;
import com.spice.profitmandi.web.req.CallbackRequest;
import com.spice.profitmandi.web.req.ResolveCallbackRequest;
import com.spice.profitmandi.web.res.AssignedRequestResponse;
import com.spice.profitmandi.web.res.CallbackReplyResponse;
import com.spice.profitmandi.web.res.CallbackRequestResponse;
import com.spice.profitmandi.web.res.SupportTeamResponse;
import com.spice.profitmandi.web.res.SupportTeamResponse.ContactDetail;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Controller
@Transactional(rollbackFor = Throwable.class)
public class SupportController {

    private static final Logger LOGGER = LogManager.getLogger(SupportController.class);

    @Autowired
    private ResponseSender<?> responseSender;

    @Autowired
    private CsService csService;

    @Autowired
    private AuthRepository authRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private CallbackRequestRepository callbackRequestRepository;

    @Autowired
    private CallbackRequestReplyRepository callbackRequestReplyRepository;

    @Autowired
    private RetailerRepository retailerRepository;

    @Autowired
    private FofoStoreRepository fofoStoreRepository;

    @RequestMapping(value = "/support/team", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Get assigned support team for a FOFO store grouped by escalation level")
    public ResponseEntity<?> getSupportTeam(HttpServletRequest request, @RequestParam(value = "fofoId") int fofoId) throws Throwable {
        LOGGER.info("Getting support team for fofoId: {}", fofoId);

        List<SupportTeamResponse> response = new ArrayList<>();

        // --- LEVEL 1 - IMMEDIATE SUPPORT ---
        List<ContactDetail> l1Contacts = new ArrayList<>();

        // RBM = RBM category, L1
        try {
            int rbmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L1, fofoId);
            if (rbmAuthUserId > 0) {
                AuthUser user = authRepository.selectById(rbmAuthUserId);
                if (user != null) {
                    l1Contacts.add(buildContact(user, "RBM", "#1a7a4c",
                            "First point of contact for all queries", true, true, false, true));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch RBM for fofoId: {}", fofoId, e);
        }

        // ABM = SALES category, L1
        try {
            int abmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L1, fofoId);
            if (abmAuthUserId > 0) {
                AuthUser user = authRepository.selectById(abmAuthUserId);
                if (user != null) {
                    l1Contacts.add(buildContact(user, "ASM", "#1a7a4c",
                            "Sales support and regional queries", true, true, false, true));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch ABM for fofoId: {}", fofoId, e);
        }

        if (!l1Contacts.isEmpty()) {
            response.add(new SupportTeamResponse("LEVEL 1 - IMMEDIATE SUPPORT", l1Contacts));
        }

        // --- LEVEL 2 - SPECIALIZED SUPPORT ---
        List<ContactDetail> l2Contacts = new ArrayList<>();

        // RBM Manager = RBM category, L2
        try {
            int rbmManagerAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_RBM, EscalationType.L2, fofoId);
            if (rbmManagerAuthUserId > 0) {
                AuthUser user = authRepository.selectById(rbmManagerAuthUserId);
                if (user != null) {
                    l2Contacts.add(buildContact(user, "RBM MANAGER", "#7c3aed",
                            "For escalated regional matters", true, true, false, true));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch RBM Manager for fofoId: {}", fofoId, e);
        }

        // BM = SALES category, L2
        try {
            int bmAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_SALES, EscalationType.L2, fofoId);
            if (bmAuthUserId > 0) {
                AuthUser user = authRepository.selectById(bmAuthUserId);
                if (user != null) {
                    l2Contacts.add(buildContact(user, "BM", "#1e6091",
                            "Handles: Orders, Stock, Schemes", true, true, false, true));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch BM for fofoId: {}", fofoId, e);
        }

        // Finance Partner Mapping Operations = FINANCIAL_SERVICES category, L2
        try {
            int affordAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_FINANCIAL_SERVICES, EscalationType.L2, fofoId);
            if (affordAuthUserId > 0) {
                AuthUser user = authRepository.selectById(affordAuthUserId);
                if (user != null) {
                    l2Contacts.add(buildContact(user, "Finance Partner Mapping", "#d97706",
                            "Credit, payment plans, and operations", false, false, true, false));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch Finance Partner Mapping Manager for fofoId: {}", fofoId, e);
        }

        // Branding Manager = DESIGN category, L1
        try {
            int brandingAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_DESIGN, EscalationType.L1, fofoId);
            if (brandingAuthUserId > 0) {
                AuthUser user = authRepository.selectById(brandingAuthUserId);
                if (user != null) {
                    l2Contacts.add(buildContact(user, "BRANDING", "#1a7a4c",
                            "Brand guidelines and marketing support", false, false, true, false));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch Branding Manager for fofoId: {}", fofoId, e);
        }

        if (!l2Contacts.isEmpty()) {
            response.add(new SupportTeamResponse("LEVEL 2 - SPECIALIZED SUPPORT", l2Contacts));
        }

        // --- LEVEL 3 - ESCALATION ---
        List<ContactDetail> l3Contacts = new ArrayList<>();

        // Grievance Manager = LEGAL category, L3
        try {
            int grievanceAuthUserId = csService.getAuthUserId(ProfitMandiConstants.TICKET_CATEGORY_CRM, EscalationType.L1, fofoId);
            if (grievanceAuthUserId > 0) {
                AuthUser user = authRepository.selectById(grievanceAuthUserId);
                if (user != null) {
                    l3Contacts.add(buildContact(user, "GRIEVANCE OFFICER", "#dc2626",
                            "For unresolved issues & formal complaints", false, false, true, true));
                }
            }
        } catch (Exception e) {
            LOGGER.warn("Could not fetch Grievance Manager for fofoId: {}", fofoId, e);
        }

        if (!l3Contacts.isEmpty()) {
            response.add(new SupportTeamResponse("LEVEL 3 - ESCALATION", l3Contacts));
        }

        return responseSender.ok(response);
    }

    @RequestMapping(value = "/support/callback-request", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Submit a callback request to a support contact")
    public ResponseEntity<?> requestCallback(HttpServletRequest request, @RequestBody CallbackRequest callbackRequest) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        User user = userRepository.selectById(userInfo.getUserId());

        LOGGER.info("Callback request from userId: {} to contactId: {} subject: {}",
                userInfo.getUserId(), callbackRequest.getContactId(), callbackRequest.getSubject());

        // Save to database
        com.spice.profitmandi.dao.entity.cs.CallbackRequest entity = new com.spice.profitmandi.dao.entity.cs.CallbackRequest();
        entity.setFofoId(userInfo.getRetailerId());
        entity.setUserId(userInfo.getUserId());
        entity.setContactId(callbackRequest.getContactId());
        entity.setContactName(callbackRequest.getContactName());
        entity.setContactRole(callbackRequest.getContactRole());
        entity.setSubject(callbackRequest.getSubject());
        entity.setMessage(callbackRequest.getMessage());
        entity.setTiming(callbackRequest.getTiming());
        entity.setStatus("PENDING");
        entity.setCreateTimestamp(LocalDateTime.now());
        entity.setUpdateTimestamp(LocalDateTime.now());
        callbackRequestRepository.persist(entity);
        LOGGER.info("Callback request saved with id: {}", entity.getId());

        String timingLabel = "11-15".equals(callbackRequest.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM";

        // Send email to the support contact
        AuthUser contactUser = authRepository.selectById(callbackRequest.getContactId());
        if (contactUser == null || contactUser.getEmailId() == null) {
            LOGGER.warn("Contact user not found or has no email for contactId: {}", callbackRequest.getContactId());
            return responseSender.ok(true);
        }

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setSubject("Callback Request: " + callbackRequest.getSubject());

        String emailContent = "<html>"
                + "<body style='font-family: Arial, sans-serif; color: #333;'>"
                + "<h2 style='color: #d5282c;'>New Callback Request</h2>"
                + "<table style='border-collapse: collapse; width: 100%; max-width: 500px;'>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>From:</td>"
                + "<td style='padding: 8px;'>" + user.getFirstName() + " (" + user.getMobileNumber() + ")</td></tr>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Email:</td>"
                + "<td style='padding: 8px;'>" + user.getEmailId() + "</td></tr>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>To:</td>"
                + "<td style='padding: 8px;'>" + callbackRequest.getContactName() + " (" + callbackRequest.getContactRole() + ")</td></tr>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Subject:</td>"
                + "<td style='padding: 8px;'>" + callbackRequest.getSubject() + "</td></tr>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Message:</td>"
                + "<td style='padding: 8px;'>" + callbackRequest.getMessage() + "</td></tr>"
                + "<tr><td style='padding: 8px; font-weight: bold; color: #555;'>Preferred Timing:</td>"
                + "<td style='padding: 8px;'>" + timingLabel + "</td></tr>"
                + "</table>"
                + "<br><p style='color: #999; font-size: 12px;'>This callback request was submitted via the SmartDukaan Support page.</p>"
                + "</body></html>";

        helper.setText(emailContent, true);
        InternetAddress senderAddress = new InternetAddress("care@smartdukaan.com", "SmartDukaan Support");
        helper.setFrom(senderAddress);
        helper.setTo(contactUser.getEmailId());
        helper.setReplyTo(user.getEmailId());

        mailSender.send(message);
        LOGGER.info("Callback request email sent to: {}", contactUser.getEmailId());

        return responseSender.ok(true);
    }

    @RequestMapping(value = "/support/callback-requests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Get callback requests for the logged-in fofo associate")
    public ResponseEntity<?> getCallbackRequests(HttpServletRequest request) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        int fofoId = userInfo.getRetailerId();
        LOGGER.info("Getting callback requests for fofoId: {}", fofoId);

        List<com.spice.profitmandi.dao.entity.cs.CallbackRequest> callbackRequests = callbackRequestRepository.selectAllByFofoId(fofoId);

        List<CallbackRequestResponse> responseList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");

        for (com.spice.profitmandi.dao.entity.cs.CallbackRequest entity : callbackRequests) {
            CallbackRequestResponse res = new CallbackRequestResponse();
            res.setId(entity.getId());
            res.setContactId(entity.getContactId());
            res.setContactName(entity.getContactName());
            res.setContactInitials(getInitials(entity.getContactName()));
            res.setContactRole(entity.getContactRole());
            res.setSubject(entity.getSubject());
            res.setMessage(entity.getMessage());
            res.setTiming(entity.getTiming());
            res.setTimingLabel("11-15".equals(entity.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM");
            res.setStatus(entity.getStatus());
            res.setResolutionNotes(entity.getResolutionNotes());
            res.setReplyCount(callbackRequestReplyRepository.countByCallbackRequestId(entity.getId()));
            res.setUnread(entity.isUnread());
            if (entity.getCreateTimestamp() != null) {
                res.setCreateTimestamp(entity.getCreateTimestamp().format(formatter));
            }
            responseList.add(res);
        }

        return responseSender.ok(responseList);
    }

    @RequestMapping(value = "/support/callback-requests/unread-count", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Get count of unread callback requests for the logged-in retailer")
    public ResponseEntity<?> getUnreadCount(HttpServletRequest request) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        int fofoId = userInfo.getRetailerId();
        LOGGER.info("Getting unread callback request count for fofoId: {}", fofoId);
        long count = callbackRequestRepository.countUnreadByFofoId(fofoId);
        return responseSender.ok(count);
    }

    @RequestMapping(value = "/support/callback-requests/mark-read", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Mark all callback requests as read for the logged-in retailer")
    public ResponseEntity<?> markRequestsAsRead(HttpServletRequest request) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        int fofoId = userInfo.getRetailerId();
        LOGGER.info("Marking all callback requests as read for fofoId: {}", fofoId);
        callbackRequestRepository.markAllReadByFofoId(fofoId);
        return responseSender.ok(true);
    }

    @RequestMapping(value = "/support/assigned-requests", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Get callback requests assigned to the logged-in internal user")
    public ResponseEntity<?> getAssignedRequests(HttpServletRequest request) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        int contactId = userInfo.getUserId();
        LOGGER.info("Getting assigned requests for contactId: {}", contactId);

        List<com.spice.profitmandi.dao.entity.cs.CallbackRequest> callbackRequests = callbackRequestRepository.selectAllByContactId(contactId);

        List<AssignedRequestResponse> responseList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");

        for (com.spice.profitmandi.dao.entity.cs.CallbackRequest entity : callbackRequests) {
            AssignedRequestResponse res = new AssignedRequestResponse();
            res.setId(entity.getId());
            res.setSubject(entity.getSubject());
            res.setMessage(entity.getMessage());
            res.setTiming(entity.getTiming());
            res.setTimingLabel("11-15".equals(entity.getTiming()) ? "11:00 AM - 3:00 PM" : "3:00 PM - 7:00 PM");
            res.setStatus(entity.getStatus());
            res.setResolutionNotes(entity.getResolutionNotes());
            res.setReplyCount(callbackRequestReplyRepository.countByCallbackRequestId(entity.getId()));

            if (entity.getCreateTimestamp() != null) {
                res.setCreateTimestamp(entity.getCreateTimestamp().format(formatter));
            }
            if (entity.getUpdateTimestamp() != null) {
                res.setUpdateTimestamp(entity.getUpdateTimestamp().format(formatter));
            }

            // Fetch retailer info
            try {
                User retailerUser = userRepository.selectById(entity.getUserId());
                if (retailerUser != null) {
                    res.setRetailerName(retailerUser.getFirstName());
                    res.setRetailerPhone(retailerUser.getMobileNumber());
                }
            } catch (Exception e) {
                LOGGER.warn("Could not fetch user for userId: {}", entity.getUserId(), e);
            }

            // Fetch store info
            try {
                Retailer retailer = retailerRepository.selectById(entity.getFofoId());
                if (retailer != null) {
                    res.setStoreName(retailer.getName());
                }
                FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(entity.getFofoId());
                if (fofoStore != null) {
                    res.setStoreCode(fofoStore.getCode());
                }
            } catch (Exception e) {
                LOGGER.warn("Could not fetch store info for fofoId: {}", entity.getFofoId(), e);
            }

            responseList.add(res);
        }

        return responseSender.ok(responseList);
    }

    @RequestMapping(value = "/support/assigned-requests/{id}/resolve", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Update status and resolution notes for a callback request")
    public ResponseEntity<?> resolveAssignedRequest(HttpServletRequest request, @PathVariable("id") int id,
                                                     @RequestBody ResolveCallbackRequest resolveRequest) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");
        LOGGER.info("Resolving callback request id: {} by userId: {} status: {}", id, userInfo.getUserId(), resolveRequest.getStatus());

        com.spice.profitmandi.dao.entity.cs.CallbackRequest entity = callbackRequestRepository.selectById(id);
        if (entity == null) {
            LOGGER.warn("Callback request not found for id: {}", id);
            return responseSender.ok(false);
        }

        entity.setStatus(resolveRequest.getStatus());
        entity.setResolutionNotes(resolveRequest.getResolutionNotes());
        entity.setUpdateTimestamp(LocalDateTime.now());
        callbackRequestRepository.persist(entity);

        LOGGER.info("Callback request id: {} resolved with status: {}", id, resolveRequest.getStatus());
        return responseSender.ok(true);
    }

    @RequestMapping(value = "/support/callback-requests/{id}/replies", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Get all replies for a callback request")
    public ResponseEntity<?> getReplies(HttpServletRequest request, @PathVariable("id") int id) throws Throwable {
        LOGGER.info("Getting replies for callback request id: {}", id);

        List<CallbackRequestReply> replies = callbackRequestReplyRepository.selectAllByCallbackRequestId(id);
        Collections.reverse(replies); // oldest first for chat order

        List<CallbackReplyResponse> responseList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");

        for (CallbackRequestReply reply : replies) {
            CallbackReplyResponse res = new CallbackReplyResponse();
            res.setId(reply.getId());
            res.setMessage(reply.getMessage());
            res.setSenderType(reply.getSenderType());
            res.setSenderName(reply.getSenderName());
            if (reply.getCreateTimestamp() != null) {
                res.setCreateTimestamp(reply.getCreateTimestamp().format(formatter));
            }
            responseList.add(res);
        }

        return responseSender.ok(responseList);
    }

    @RequestMapping(value = "/support/callback-requests/{id}/reply", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({@ApiImplicitParam(name = "Auth-Token", value = "Auth-Token", required = true, dataType = "string", paramType = "header")})
    @ApiOperation(value = "Add a reply to a callback request")
    public ResponseEntity<?> addReply(HttpServletRequest request, @PathVariable("id") int id,
                                       @RequestBody CallbackReplyRequest replyRequest) throws Throwable {
        UserInfo userInfo = (UserInfo) request.getAttribute("userInfo");

        com.spice.profitmandi.dao.entity.cs.CallbackRequest callbackReq = callbackRequestRepository.selectById(id);
        if (callbackReq == null) {
            LOGGER.warn("Callback request not found for id: {}", id);
            return responseSender.ok(false);
        }

        // Determine sender type: if userId matches the request creator, it's RETAILER; otherwise INTERNAL
        String senderType = (userInfo.getUserId() == callbackReq.getUserId()) ? "RETAILER" : "INTERNAL";
        User senderUser = userRepository.selectById(userInfo.getUserId());
        String senderName = senderUser != null ? senderUser.getFirstName() : "Unknown";

        LOGGER.info("Adding reply to callback request id: {} by userId: {} senderType: {}", id, userInfo.getUserId(), senderType);

        CallbackRequestReply reply = new CallbackRequestReply();
        reply.setCallbackRequestId(id);
        reply.setMessage(replyRequest.getMessage());
        reply.setSenderType(senderType);
        reply.setSenderName(senderName);
        reply.setSenderId(userInfo.getUserId());
        reply.setCreateTimestamp(LocalDateTime.now());
        callbackRequestReplyRepository.persist(reply);

        // Update the parent request's updateTimestamp
        callbackReq.setUpdateTimestamp(LocalDateTime.now());
        // Mark as unread for the retailer when an internal user replies
        if ("INTERNAL".equals(senderType)) {
            callbackReq.setUnread(true);
        }
        callbackRequestRepository.persist(callbackReq);

        LOGGER.info("Reply added with id: {} to callback request id: {}", reply.getId(), id);
        return responseSender.ok(true);
    }

    private ContactDetail buildContact(AuthUser authUser, String badge, String badgeColor,
                                       String description, boolean showCall, boolean showMessage,
                                       boolean showCallback, boolean expanded) {
        ContactDetail contact = new ContactDetail();
        contact.setId(authUser.getId());
        contact.setName(authUser.getFullName());
        contact.setInitials(getInitials(authUser.getFirstName(), authUser.getLastName()));
        contact.setRole(badge);
        contact.setBadge(badge);
        contact.setBadgeColor(badgeColor);
        contact.setDescription(description);
        contact.setPhone("tel:+91" + authUser.getMobileNumber());
        contact.setWhatsapp("https://wa.me/91" + authUser.getMobileNumber());
        contact.setEmail(authUser.getEmailId());
        contact.setShowCall(showCall);
        contact.setShowMessage(showMessage);
        contact.setShowCallback(showCallback);
        contact.setExpanded(expanded);
        return contact;
    }

    private String getInitials(String firstName, String lastName) {
        StringBuilder initials = new StringBuilder();
        if (firstName != null && !firstName.isEmpty()) {
            initials.append(firstName.charAt(0));
        }
        if (lastName != null && !lastName.isEmpty()) {
            initials.append(lastName.charAt(0));
        }
        return initials.toString().toUpperCase();
    }

    private String getInitials(String fullName) {
        if (fullName == null || fullName.isEmpty()) {
            return "";
        }
        String[] parts = fullName.trim().split("\\s+");
        StringBuilder initials = new StringBuilder();
        initials.append(parts[0].charAt(0));
        if (parts.length > 1) {
            initials.append(parts[parts.length - 1].charAt(0));
        }
        return initials.toString().toUpperCase();
    }
}