package com.example.backend.categories.service;

import java.util.List;

import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.example.backend.categories.model.CategoryEntity;
import com.example.backend.categories.repository.CategoryRepository;
import com.example.backend.core.error.NotFoundException;

@Service
public class CategoryService {
    private final CategoryRepository repository;

    public CategoryService(CategoryRepository repository) {
        this.repository = repository;
    }

    private void checkName(String name) {
        if (repository.findByNameIgnoreCase(name).isPresent()) {
            throw new IllegalArgumentException(
                    String.format("Category with name %s is already exists", name));
        }
    }

    @Transactional(readOnly = true)
    public List<CategoryEntity> getAll() {
        Sort sortById = Sort.by(Sort.Direction.ASC, "id");
        return repository.findAll(sortById);
    }

    @Transactional(readOnly = true)
    public CategoryEntity get(long id) {
        return repository.findById(id)
                .orElseThrow(() -> new NotFoundException(CategoryEntity.class, id));
    }

    @Transactional
    public CategoryEntity create(CategoryEntity entity) {
        if (entity == null) {
            throw new IllegalArgumentException("Entity is null");
        }
        checkName(entity.getName());
        return repository.save(entity);
    }

    @Transactional
    public CategoryEntity update(long id, CategoryEntity entity) {
        final CategoryEntity existsEntity = get(id);
        existsEntity.setName(entity.getName());
        return repository.save(existsEntity);
    }

    @Transactional
    public CategoryEntity delete(long id) {
        final CategoryEntity existsEntity = get(id);
        repository.delete(existsEntity);
        return existsEntity;
    }
}
