package org.fuseri.modulelanguageschool.common;

import jakarta.persistence.EntityNotFoundException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

public abstract class DomainService<T extends DomainObject> {

    public static final int DEFAULT_PAGE_SIZE = 10;

    public abstract JpaRepository<T, Long> getRepository();

    @Transactional
    public T create(T entity) {
        return getRepository().save(entity);
    }

    @Transactional(readOnly = true)
    public Page<T> findAll(Pageable pageable) {
        return getRepository().findAll(pageable);
    }

    @Transactional(readOnly = true)
    public Page<T> findAll(int page) {
        return getRepository().findAll(PageRequest.of(page, DEFAULT_PAGE_SIZE));
    }

    /**
     * Delete an entity with specified id
     * @param id id of the entity to delete
     */
    public void delete(long id) {
        getRepository().deleteById(id);
    }

    /**
     * Update an entity
     *
     * @param id the entity ID
     * @param entity the entity to update
     * @return the updated entity
     */
    public T update(Long id, T entity) {
        if (!getRepository().existsById(id)) {
            throw new EntityNotFoundException("Entity with id " + entity.getId() + " not found.");
        }
        entity.setId(id);
        return getRepository().save(entity);
    }
}
