package at.procon.dip.domain.document.service;

import at.procon.dip.domain.document.entity.DocumentRelation;
import at.procon.dip.domain.document.repository.DocumentRelationRepository;
import at.procon.dip.domain.document.service.command.CreateDocumentRelationCommand;
import java.util.List;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional
public class DocumentRelationService {

    private final DocumentService documentService;
    private final DocumentRelationRepository relationRepository;

    public DocumentRelation createRelation(CreateDocumentRelationCommand command) {
        DocumentRelation relation = DocumentRelation.builder()
                .parentDocument(documentService.getRequired(command.parentDocumentId()))
                .childDocument(documentService.getRequired(command.childDocumentId()))
                .relationType(command.relationType())
                .sortOrder(command.sortOrder())
                .relationMetadata(command.relationMetadata())
                .build();
        return relationRepository.save(relation);
    }

    public DocumentRelation ensureRelation(CreateDocumentRelationCommand command) {
        boolean exists = relationRepository.existsByParentDocument_IdAndChildDocument_IdAndRelationType(
                command.parentDocumentId(), command.childDocumentId(), command.relationType());
        if (exists) {
            return relationRepository.findByParentDocument_IdAndRelationType(command.parentDocumentId(), command.relationType())
                    .stream()
                    .filter(rel -> rel.getChildDocument() != null && command.childDocumentId().equals(rel.getChildDocument().getId()))
                    .findFirst()
                    .orElseGet(() -> createRelation(command));
        }
        return createRelation(command);
    }

    @Transactional(readOnly = true)
    public List<DocumentRelation> findChildren(UUID parentDocumentId) {
        return relationRepository.findByParentDocument_Id(parentDocumentId);
    }
}
