package repositories

import (
	dto "astrology-api/dto"

	"gorm.io/gorm"
)

type ChatHistoryRepository interface {

	// Chat History List
	GetChatHistory(
		userID uint,
		page int,
		limit int,
		search string,
		status string,
	) ([]dto.ChatHistoryResponse, int64, error)
}

type chatHistoryRepository struct {
	db *gorm.DB
}

func NewChatHistoryRepository(db *gorm.DB) ChatHistoryRepository {
	return &chatHistoryRepository{
		db: db,
	}
}

func (r *chatHistoryRepository) GetChatHistory(
	userID uint,
	page int,
	limit int,
	search string,
	status string,
) ([]dto.ChatHistoryResponse, int64, error) {

	var histories []dto.ChatHistoryResponse
	var totalRecords int64

	offset := (page - 1) * limit

	query := r.db.
		Table("user_chat_histories uch").
		Joins("LEFT JOIN astrologers a ON a.id = uch.astrologerId").
		Where("uch.userId = ?", userID).
		Where("uch.isDelete = ?", false).
		Where("uch.isActive = ?", true)

	// Search
	if search != "" {

		query = query.Where(`
			uch.chatHistoryNumber LIKE ?
			OR uch.name LIKE ?
			OR a.name LIKE ?
		`,
			"%"+search+"%",
			"%"+search+"%",
			"%"+search+"%",
		)
	}

	// Status Filter
	if status != "" {

		query = query.Where("uch.chatStatus = ?", status)

	}

	// Count
	if err := query.Count(&totalRecords).Error; err != nil {

		return nil, 0, err

	}

	// Data

	err := query.
		Select(`
			uch.id,
			uch.chatHistoryNumber,
			uch.chatStatus,
			uch.chatDuration,
			uch.deductionAmount,
			uch.chatType,
			uch.name,
			uch.birthDate,
			uch.birthTime,
			uch.birthPlace,
			uch.gender,
			uch.created_at,

			a.id as astrologer_id,
			a.name as astrologer_name,
			a.profileImage as astrologer_profile_image,
			a.experience as astrologer_experience,
			a.rating as astrologer_rating
		`).
		Order("uch.id DESC").
		Limit(limit).
		Offset(offset).
		Scan(&histories).Error

	if err != nil {

		return nil, 0, err

	}

	return histories, totalRecords, nil

}