package services

import (
	"errors"

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

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

type EducationService struct{}

func NewEducationService() *EducationService {
	return &EducationService{}
}

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

func (s *EducationService) CreateEducation(betweenYears, title, content string, resumeID *uuid.UUID, isActive bool) (*models.Education, error) {
	item := models.Education{
		BetweenYears: betweenYears,
		Title:        title,
		Content:      content,
		ResumeID:     resumeID,
		IsActive:     isActive,
	}

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

func (s *EducationService) UpdateEducation(id string, betweenYears, title, content *string, resumeID *uuid.UUID, isActive *bool) (*models.Education, error) {
	item, err := s.GetEducationByID(id)
	if err != nil {
		return nil, err
	}

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

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