package org.takiguchi.cerberus.cerberusapp.persistence.adapter;


import org.springframework.stereotype.Component;
import org.takiguchi.cerberus.cerberusapp.model.Application;
import org.takiguchi.cerberus.cerberusapp.persistence.mapper.ApplicationEntityMapper;
import org.takiguchi.cerberus.cerberusapp.persistence.model.ApplicationEntity;
import org.takiguchi.cerberus.cerberusapp.persistence.repository.ApplicationRepository;
import org.takiguchi.cerberus.cerberusapp.service.ApplicationRepositoryPort;

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

@Component
public class ApplicationJpaRepositoryAdapter implements ApplicationRepositoryPort {
    private final ApplicationRepository repository;
    private final ApplicationEntityMapper applicationMapper;

    public ApplicationJpaRepositoryAdapter(ApplicationRepository repository,
                                           ApplicationEntityMapper applicationMapper) {
        this.repository = repository;
        this.applicationMapper = applicationMapper;
    }

    @Override
    public Optional<Application> getById(UUID applicationId) {
        return repository.findById(applicationId)
                .map(applicationMapper::mapToDomain);
    }

    @Override
    public List<Application> getAll() {
        return repository.findAll()
                .stream()
                .map(applicationMapper::mapToDomain)
                .collect(Collectors.toList());
    }

    @Override
    public Application add(Application application) {
        ApplicationEntity entityToSave = applicationMapper.mapToEntity(application);
        ApplicationEntity savedApplication = repository.save(entityToSave);
        return applicationMapper.mapToDomain(savedApplication);
    }

    @Override
    public void update(Application application) {
        ApplicationEntity entityToSave = applicationMapper.mapToEntity(application);
        repository.save(entityToSave);
    }

    @Override
    public void remove(UUID applicationId) {
        repository.deleteById(applicationId);
    }
}
