package org.fuseri.modulelanguageschool.user;

import jakarta.persistence.EntityNotFoundException;
import lombok.Getter;
import org.fuseri.modulelanguageschool.common.DomainService;
import org.fuseri.modulelanguageschool.common.UserWithEmailAlreadyExists;
import org.fuseri.modulelanguageschool.course.Course;
import org.fuseri.modulelanguageschool.course.Language;
import org.fuseri.modulelanguageschool.course.ProficiencyLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class UserService extends DomainService<User> {

    @Getter
    private final UserRepository repository;

    @Autowired
    public UserService(UserRepository repository) {
        this.repository = repository;
    }

    @Override
    public User create(User entity) {
        if (repository.existsByEmail(entity.getEmail())) {
            throw new UserWithEmailAlreadyExists("User with " + entity.getEmail() + " already exists.");
        }
        return super.create(entity);
    }

    @Transactional(readOnly = true)
    public User find(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("User " + id + "' not found."));
    }

    public Optional<User> findUserByEmail(String email) {
        return repository.findByEmail(email);
    }

    public List<Course> getEnrolled(Long id) {
        return repository.getEnrolled(id);
    }

    public List<Course> getFinished(Long id) {
        return repository.getFinished(id);
    }

    public User addLanguageProficiency(Long id, Language language, ProficiencyLevel proficiency) {
        Optional<User> optionalUser = repository.findById(id);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            user.addLanguageProficiency(language, proficiency);
            return repository.save(user);
        } else {
            throw new EntityNotFoundException("User '" + id + "' not found.");
        }
    }

}
