package services

import (
	"errors"

	"gauth-central/internal/database"
	"gauth-central/internal/models"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

type KnowledgeService struct{}

func NewKnowledgeService() *KnowledgeService {
	return &KnowledgeService{}
}

func (s *KnowledgeService) GetAllKnowledges(resumeID *string, onlyActive bool) ([]models.Knowledge, error) {
	var items []models.Knowledge
	query := database.DB.Order("created_at desc")

	if resumeID != nil {
		query = query.Where("resume_id = ?", *resumeID)
	}

	if onlyActive {
		query = query.Where("is_active = ?", true)
	}

	if err := query.Find(&items).Error; err != nil {
		return nil, err
	}
	return items, nil
}

func (s *KnowledgeService) GetKnowledgeByID(id string) (*models.Knowledge, error) {
	var item models.Knowledge
	if err := database.DB.Where("id = ?", id).First(&item).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("knowledge not found")
		}
		return nil, err
	}
	return &item, nil
}

func (s *KnowledgeService) CreateKnowledge(title string, resumeID *uuid.UUID, isActive bool) (*models.Knowledge, error) {
	item := models.Knowledge{
		Title:    title,
		ResumeID: resumeID,
		IsActive: isActive,
	}

	if err := database.DB.Create(&item).Error; err != nil {
		return nil, err
	}
	return &item, nil
}

func (s *KnowledgeService) UpdateKnowledge(id string, title *string, resumeID *uuid.UUID, isActive *bool) (*models.Knowledge, error) {
	item, err := s.GetKnowledgeByID(id)
	if err != nil {
		return nil, err
	}

	updates := map[string]interface{}{}
	if title != nil {
		updates["title"] = *title
	}
	if resumeID != nil {
		updates["resume_id"] = *resumeID
	}
	if isActive != nil {
		updates["is_active"] = *isActive
	}

	if len(updates) > 0 {
		if err := database.DB.Model(item).Updates(updates).Error; err != nil {
			return nil, err
		}
	}
	return s.GetKnowledgeByID(id)
}

func (s *KnowledgeService) DeleteKnowledge(id string) error {
	result := database.DB.Delete(&models.Knowledge{}, "id = ?", id)
	if result.Error != nil {
		return result.Error
	}
	if result.RowsAffected == 0 {
		return errors.New("knowledge not found")
	}
	return nil
}
