package repositories

import (
	"astrology-api/dto"

	"gorm.io/gorm"
)

type CallHistoryRepository interface {

	// Get Call History
	GetCallHistory(
		userID uint,
		page int,
		limit int,
		search string,
		status string,
	) ([]dto.CallHistoryResponse, int64, error)
}

type callHistoryRepository struct {
	db *gorm.DB
}

func NewCallHistoryRepository(db *gorm.DB) CallHistoryRepository {
	return &callHistoryRepository{
		db: db,
	}
}

func (r *callHistoryRepository) GetCallHistory(
	userID uint,
	page int,
	limit int,
	search string,
	status string,
) ([]dto.CallHistoryResponse, int64, error) {

	var histories []dto.CallHistoryResponse
	var totalRecords int64

	offset := (page - 1) * limit

	query := r.db.
		Table("user_call_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.callHistoryNumber LIKE ?
			OR uch.name LIKE ?
			OR a.name LIKE ?
		`,
			"%"+search+"%",
			"%"+search+"%",
			"%"+search+"%",
		)
	}

	// Status Filter
	if status != "" {

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

	}

	// Total Records
	if err := query.Count(&totalRecords).Error; err != nil {
		return nil, 0, err
	}

	// Fetch Records
	err := query.
		Select(`
			uch.id,
			uch.callHistoryNumber,
			uch.callStatus,
			uch.callDuration,
			uch.deductionAmount,
			uch.callType,
			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
}