package enea.lecservice.services;

import enea.lecservice.entities.Permission;
import enea.lecservice.entities.Role;
import enea.lecservice.models.dto.ServiceResponse;
import enea.lecservice.repository.PermissionRepository;
import enea.lecservice.repository.RoleRepository;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class PermissionsService {

    @NonNull PermissionRepository permissionRepository;
    @NonNull RoleRepository roleRepository;

    public ServiceResponse initData() {
        try {

            var roles = new String[] { "registered", "platform-admin" };

            for (var role : roles)
                if (!roleRepository.existsById(role))
                    roleRepository.save(Role.builder().id(role).description(role).build());

            var permissions = new String[] { "admin" };

            for (var permission: permissions)
                if (!permissionRepository.existsById(permission))
                    permissionRepository.save(Permission.builder().id(permission).description(permission).build());

            return ServiceResponse.Success();
        }
        catch (Exception e) {
            return ServiceResponse.Error(e);
        }
    }

    public ServiceResponse<List<Permission>> findAll() {
        return ServiceResponse.Success(permissionRepository.findAll());
    }
}
