package org.fuseri.moduleexercise.common;

import jakarta.persistence.EntityNotFoundException;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * Represent common service for managing entities
 *
 * @param <T> the type of entity managed by this service
 */
public abstract class DomainService<T extends DomainObject> {

    /**
     * The default page size used for pagination
     */
    public static final int DEFAULT_PAGE_SIZE = 10;

    /**
     * Return the repository used by this service
     *
     * @return the repository used by this service
     */
    public abstract JpaRepository<T, Long> getRepository();

    /**
     * Create an entity by saving it to the repository
     *
     * @param entity the entity to create
     * @return the created entity
     */
    public T create(T entity) {
        return getRepository().save(entity);
    }

    /**
     * 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);
    }

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

}