package repository

import (
	"fmt"
	"narasi-ahli-be/app/database"
	"narasi-ahli-be/app/database/entity"
	"narasi-ahli-be/app/module/knowledge_base/request"
	"narasi-ahli-be/utils/paginator"
	"strings"
	"time"
)

type KnowledgeBaseRepository struct {
	DB *database.Database
}

// interface
type KnowledgeBaseRepositoryInterface interface {
	GetAll(req request.KnowledgeBaseQueryRequest) (data []*entity.KnowledgeBase, paging paginator.Pagination, err error)
	FindOne(id uint) (data *entity.KnowledgeBase, err error)
	FindByFilename(filename string) (data *entity.KnowledgeBase, fileType string, err error)

	Create(data *entity.KnowledgeBase) (err error)
	Update(id uint, data *entity.KnowledgeBase) (err error)
	Delete(id uint) (err error)
	UpdateDocumentId(id uint, documentId int) error

}

func NewKnowledgeBaseRepository(db *database.Database) KnowledgeBaseRepositoryInterface {
	return &KnowledgeBaseRepository{
		DB: db,
	}
}

func (r *KnowledgeBaseRepository) GetAll(req request.KnowledgeBaseQueryRequest) (data []*entity.KnowledgeBase, paging paginator.Pagination, err error) {
	var count int64

	query := r.DB.DB.Model(&entity.KnowledgeBase{})

	query = query.Where("is_active = ?", true)

	if req.AgentId != nil && *req.AgentId != "" {
		query = query.Where("agent_id = ?", *req.AgentId)
	}

	if req.CreatedById != nil && *req.CreatedById > 0 {
		query = query.Where("created_by_id = ?", *req.CreatedById)
	}

	if req.Title != nil && strings.TrimSpace(*req.Title) != "" {
		title := strings.ToLower(strings.TrimSpace(*req.Title))
		query = query.Where("LOWER(title) LIKE ?", "%"+title+"%")
	}

	if req.Status != nil {
		query = query.Where("status = ?", *req.Status)
	}

	if req.IsActive != nil {
		query = query.Where("is_active = ?", *req.IsActive)
	}

	query.Count(&count)

	if req.Pagination != nil && req.Pagination.SortBy != "" {
		direction := "ASC"
		if strings.ToLower(req.Pagination.Sort) == "desc" {
			direction = "DESC"
		}
		query = query.Order(fmt.Sprintf("%s %s", req.Pagination.SortBy, direction))
	} else {
		query = query.Order("created_at DESC")
	}

	if req.Pagination == nil {
		req.Pagination = &paginator.Pagination{}
	}
	req.Pagination.Count = count
	req.Pagination = paginator.Paging(req.Pagination)

	err = query.
		Offset(req.Pagination.Offset).
		Limit(req.Pagination.Limit).
		Find(&data).Error

	if err != nil {
		return nil, paging, err
	}

	paging = *req.Pagination
	return data, paging, nil
}

func (r *KnowledgeBaseRepository) FindOne(id uint) (data *entity.KnowledgeBase, err error) {
	query := r.DB.DB.Model(&entity.KnowledgeBase{})

	if err := query.Where("id = ? AND is_active = ?", id, true).First(&data).Error; err != nil {
		return nil, err
	}

	return data, nil
}

func (r *KnowledgeBaseRepository) Create(data *entity.KnowledgeBase) (err error) {
	return r.DB.DB.Create(data).Error
}

func (r *KnowledgeBaseRepository) Update(id uint, data *entity.KnowledgeBase) error {
	data.UpdatedAt = time.Now()

	return r.DB.DB.Model(&entity.KnowledgeBase{}).
		Where("id = ?", id).
		Updates(data).Error
}

func (r *KnowledgeBaseRepository) Delete(id uint) (err error) {
	return r.DB.DB.Delete(&entity.KnowledgeBase{}, id).Error
}

func (r *KnowledgeBaseRepository) FindByFilename(filename string) (*entity.KnowledgeBase, string, error) {

	var kb entity.KnowledgeBase
	like := "%" + filename

	if err := r.DB.DB.
		Where("is_active = ?", true).
		Where("file_journal_url LIKE ?", like).
		First(&kb).Error; err == nil {
		return &kb, "journal", nil
	}

	if err := r.DB.DB.
		Where("is_active = ?", true).
		Where("file_audio_url LIKE ?", like).
		First(&kb).Error; err == nil {
		return &kb, "audio", nil
	}

	if err := r.DB.DB.
		Where("is_active = ?", true).
		Where("file_video_url LIKE ?", like).
		First(&kb).Error; err == nil {
		return &kb, "video", nil
	}

	return nil, "", fmt.Errorf("file not found")
}

func (r *KnowledgeBaseRepository) UpdateDocumentId(id uint, documentId int) error {
	return r.DB.DB.Model(&entity.KnowledgeBase{}).
		Where("id = ?", id).
		Updates(map[string]interface{}{
			"document_id": documentId,
			"updated_at":  time.Now(),
		}).Error
}