package services

import (
	"errors"

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

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

type ExperienceService struct{}

func NewExperienceService() *ExperienceService {
	return &ExperienceService{}
}

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

func (s *ExperienceService) CreateExperience(betweenYears, title, content string, resumeID *uuid.UUID, isActive bool) (*models.Experience, error) {
	item := models.Experience{
		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 *ExperienceService) UpdateExperience(id string, betweenYears, title, content *string, resumeID *uuid.UUID, isActive *bool) (*models.Experience, error) {
	item, err := s.GetExperienceByID(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.GetExperienceByID(id)
}

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