package services

import (
	"errors"

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

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

type SkillService struct{}

func NewSkillService() *SkillService {
	return &SkillService{}
}

func (s *SkillService) GetAllSkills(resumeID *string, onlyActive bool) ([]models.Skill, error) {
	var items []models.Skill
	query := database.DB.Order("degree 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 *SkillService) GetSkillByID(id string) (*models.Skill, error) {
	var item models.Skill
	if err := database.DB.Where("id = ?", id).First(&item).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("skill not found")
		}
		return nil, err
	}
	return &item, nil
}

func (s *SkillService) CreateSkill(title string, degree int, resumeID *uuid.UUID, isActive bool) (*models.Skill, error) {
	item := models.Skill{
		Title:    title,
		Degree:   degree,
		ResumeID: resumeID,
		IsActive: isActive,
	}

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

func (s *SkillService) UpdateSkill(id string, title *string, degree *int, resumeID *uuid.UUID, isActive *bool) (*models.Skill, error) {
	item, err := s.GetSkillByID(id)
	if err != nil {
		return nil, err
	}

	updates := map[string]interface{}{}
	if title != nil {
		updates["title"] = *title
	}
	if degree != nil {
		updates["degree"] = *degree
	}
	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.GetSkillByID(id)
}

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