package com.example.demo.news.service;

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

import com.example.demo.core.error.NotFoundException;
import com.example.demo.news.model.NewsEntity;
import com.example.demo.news.repository.NewsRepository;

@Service
public class NewsService {
    private final NewsRepository repository;

    public NewsService(NewsRepository repository) {
        this.repository = repository;
    }

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

    @Transactional(readOnly = true)
    public Page<NewsEntity> getAll(int page, int size, Long departmentId, String description){
        final Pageable pageRequest = PageRequest.of(page, size, Sort.by("id"));
        
        if(departmentId != null && (description == null || description.isEmpty())){
            return repository.findByDepartmentId(pageRequest, departmentId);
        }
        else if(departmentId == null && description != null){
            return repository.findWithSearch(pageRequest, description);
        }
        else if(departmentId != null && description != null){
            return repository.findByDepartmentIdSearch(pageRequest, departmentId, description);
        }
        return repository.findAll(pageRequest);
    }

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

    @Transactional
    public NewsEntity create(NewsEntity entity) {
        checkName(entity.getName());
        return repository.save(entity);
    }

    @Transactional
    public NewsEntity update(Long id, NewsEntity entity) {
        final NewsEntity existsEntity = get(id);
        existsEntity.setDate(entity.getDate());
        existsEntity.setName(entity.getName());
        existsEntity.setDescription(entity.getDescription());
        existsEntity.setDepartment(entity.getDepartment());
        return repository.save(existsEntity);
    }

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