package mapper

import (
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/communications/response"
)

func ConversationsResponseMapper(conversation *entity.Conversations) *response.ConversationsResponse {
	result := &response.ConversationsResponse{
		ID:             conversation.ID,
		Participant1ID: conversation.Participant1ID,
		Participant2ID: conversation.Participant2ID,
		LastMessageAt:  conversation.LastMessageAt,
		CreatedAt:      conversation.CreatedAt,
		UpdatedAt:      conversation.UpdatedAt,
	}

	if conversation.Participant1 != nil {
		result.Participant1 = &response.UserBasicInfo{
			ID:       conversation.Participant1.ID,
			Username: conversation.Participant1.Username,
			Fullname: conversation.Participant1.Fullname,
			Email:    conversation.Participant1.Email,
		}
	}

	if conversation.Participant2 != nil {
		result.Participant2 = &response.UserBasicInfo{
			ID:       conversation.Participant2.ID,
			Username: conversation.Participant2.Username,
			Fullname: conversation.Participant2.Fullname,
			Email:    conversation.Participant2.Email,
		}
	}

	return result
}

func ChatMessagesResponseMapper(chatMessage *entity.ChatMessages) *response.ChatMessagesResponse {
	result := &response.ChatMessagesResponse{
		ID:             chatMessage.ID,
		ConversationID: chatMessage.ChatSessionID,
		SenderID:       chatMessage.SenderID,
		MessageText:    &chatMessage.Message,
		MessageType:    chatMessage.MessageType,
		FileURL:        nil,   // Not available in entity
		FileName:       nil,   // Not available in entity
		FileSize:       nil,   // Not available in entity
		IsRead:         false, // Not available in entity, default to false
		CreatedAt:      chatMessage.CreatedAt,
	}

	if chatMessage.Sender != nil {
		result.Sender = &response.UserBasicInfo{
			ID:       chatMessage.Sender.ID,
			Username: chatMessage.Sender.Username,
			Fullname: chatMessage.Sender.Fullname,
			Email:    chatMessage.Sender.Email,
		}
	}

	return result
}

func ConversationWithMessagesResponseMapper(conversation *entity.Conversations, messages []*entity.ChatMessages, unreadCount int) *response.ConversationWithMessagesResponse {
	conversationResponse := ConversationsResponseMapper(conversation)
	conversationResponse.UnreadCount = unreadCount

	var messagesResponse []*response.ChatMessagesResponse
	for _, message := range messages {
		messagesResponse = append(messagesResponse, ChatMessagesResponseMapper(message))
	}

	return &response.ConversationWithMessagesResponse{
		Conversation: conversationResponse,
		Messages:     messagesResponse,
	}
}
