package com.iqser.red.service.persistence.management.v1.processor.service.persistence;

import java.time.OffsetDateTime;
import java.util.List;

import jakarta.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.iqser.red.service.persistence.management.v1.processor.entity.annotations.ViewedPageEntity;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.FileRepository;
import com.iqser.red.service.persistence.management.v1.processor.service.persistence.repository.ViewedPagesRepository;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class ViewedPagesPersistenceService {

    private final ViewedPagesRepository viewedPagesRepository;
    private final FileRepository fileRepository;


    @Transactional
    public void insertPage(String fileId, String userId, int page) {

        var id = new ViewedPageEntity.ViewedPageId(fileId, page, userId);
        viewedPagesRepository.findById(id).ifPresentOrElse(viewedPage -> viewedPage.setViewedTime(OffsetDateTime.now()), () -> {
            var viewedPage = new ViewedPageEntity();
            viewedPage.setViewedTime(OffsetDateTime.now());
            viewedPage.setId(new ViewedPageEntity.ViewedPageId(null, page, userId));
            viewedPage.setFile(fileRepository.getOne(fileId));
            viewedPagesRepository.save(viewedPage);
        });
    }


    @Transactional
    public void removePage(String fileId, String role, int page) {

        viewedPagesRepository.deleteById(new ViewedPageEntity.ViewedPageId(fileId, page, role));
    }


    public List<ViewedPageEntity> findViewedPages(String fileId, String userId) {

        return viewedPagesRepository.findByFileIdAndIdUserId(fileId, userId);
    }


    @Transactional(Transactional.TxType.REQUIRES_NEW)
    public void deleteForFile(String fileId) {

        viewedPagesRepository.deleteByFileId(fileId);
    }


    @Transactional
    public void resetViewedPages(String fileId, String currentReviewer, List<Integer> viewedPagesToReset) {

        viewedPagesRepository.deleteSeenPages(fileId, currentReviewer, viewedPagesToReset);
    }

}
