package services

import (
	dto "astrology-api/dto"
	repositories "astrology-api/repositories"
)

type ChatHistoryService interface {

	// Get Chat History
	GetChatHistory(
		userID uint,
		req *dto.GetChatHistoryRequest,
	) (*dto.ChatHistoryListResponse, error)
}

type chatHistoryService struct {
	repository repositories.ChatHistoryRepository
}

func NewChatHistoryService(
	repository repositories.ChatHistoryRepository,
) ChatHistoryService {

	return &chatHistoryService{
		repository: repository,
	}
}

//
// Get Chat History
//
func (s *chatHistoryService) GetChatHistory(
	userID uint,
	req *dto.GetChatHistoryRequest,
) (*dto.ChatHistoryListResponse, error) {

	// Default Pagination
	if req.Page <= 0 {
		req.Page = 1
	}

	if req.Limit <= 0 {
		req.Limit = 20
	}

	records, totalRecords, err := s.repository.GetChatHistory(
		userID,
		req.Page,
		req.Limit,
		req.Search,
		req.Status,
	)

	if err != nil {
		return nil, err
	}

	// Convert flat astrologer fields into nested object
	for i := range records {

		records[i].Astrologer = dto.AstrologerBrief{
			ID:           records[i].AstrologerID,
			Name:         records[i].AstrologerName,
			ProfileImage: records[i].AstrologerProfileImage,
			Experience:   records[i].AstrologerExperience,
		}
	}

	response := &dto.ChatHistoryListResponse{
		RecordList:  records,
		TotalRecord: totalRecords,
		CurrentPage: req.Page,
		Limit:       req.Limit,
		Status:      200,
	}

	return response, nil
}