package ru.ibs.socrates.confexporter.dao.service.impl;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.ibs.socrates.confexporter.dao.dto.ProjectDaoDto;
import ru.ibs.socrates.confexporter.dao.mapper.ProjectDaoMapper;
import ru.ibs.socrates.confexporter.dao.repository.ProjectRepository;
import ru.ibs.socrates.confexporter.dao.service.ProjectDaoService;


/**
 * Сервис для работы с сущностью project.
 */
@Transactional
@Slf4j
@Service
@RequiredArgsConstructor
public class ProjectDaoServiceImpl implements ProjectDaoService {
  
  private final ProjectRepository projectRepository;
  private final ProjectDaoMapper projectDaoMapper;

  @Override
  public ProjectDaoDto getBySourceId(UUID sourceId) {
    return Optional.ofNullable(sourceId)
        .flatMap(projectRepository::findBySourceId)
        .map(projectDaoMapper::toProjectDto)
        .orElseThrow();
  }
  
  /**
   * Получение проектов, которые были изменены после.
   * @param timestamp
   * @return
   */
  @Override
  @Transactional(readOnly = true)
  public List<ProjectDaoDto> getProjectUpdateAfter(OffsetDateTime timestamp) {
    return projectRepository.findAllByUpdatedAfter(timestamp)
        .stream()
        .map(projectDaoMapper::toProjectDto)
        .toList();
  }

}
