package de.avatic.lcc.service.users;

import de.avatic.lcc.dto.users.GroupDTO;
import de.avatic.lcc.model.db.users.Group;
import de.avatic.lcc.repositories.pagination.SearchQueryPagination;
import de.avatic.lcc.repositories.pagination.SearchQueryResult;
import de.avatic.lcc.repositories.users.GroupRepository;
import org.springframework.stereotype.Service;

/**
 * Service class for managing group-related operations such as updating groups
 * and retrieving group data.
 */
@Service
public class GroupService {
    private final GroupRepository groupRepository;

    public GroupService(GroupRepository groupRepository) {
        this.groupRepository = groupRepository;
    }

    /**
     * Updates an existing group in the repository.
     *
     * @param group the {@link GroupDTO} object containing updated group information
     */
    public void updateGroup(GroupDTO group) {
        groupRepository.updateGroup(fromGroupDTO(group));
    }

    /**
     * Retrieves a paginated list of groups from the repository.
     *
     * @param page  the page number to retrieve
     * @param limit the maximum number of groups returned per page
     * @return a {@link SearchQueryResult} containing {@link GroupDTO} objects and pagination metadata
     */
    public SearchQueryResult<GroupDTO> listGroups(int page, int limit) {
        return SearchQueryResult.map(groupRepository.listGroups(new SearchQueryPagination(page, limit)), this::toGroupDTO);
    }

    /**
     * Maps a {@link GroupDTO} object to a {@link Group} entity.
     *
     * @param dto the {@link GroupDTO} to be mapped
     * @return a {@link Group} entity with data populated from the DTO
     */
    private Group fromGroupDTO(GroupDTO dto) {
        var group = new Group();

        group.setDescription(dto.getDescription());
        group.setName(dto.getName());

        return group;
    }

    /**
     * Maps a {@link Group} entity to a {@link GroupDTO}.
     *
     * @param group the {@link Group} entity to be mapped
     * @return a {@link GroupDTO} containing data from the entity
     */
    private GroupDTO toGroupDTO(Group group) {
        var dto = new GroupDTO();

        dto.setId(group.getId());
        dto.setDescription( group.getDescription());
        dto.setName(group.getName());

        return dto;

    }
}
