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

import at.procon.dip.domain.document.entity.DocumentContent;
import at.procon.dip.domain.document.repository.DocumentContentRepository;
import at.procon.dip.domain.document.service.command.AddDocumentContentCommand;
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 DocumentContentService {

    private final DocumentService documentService;
    private final DocumentContentRepository contentRepository;

    public DocumentContent addContent(AddDocumentContentCommand command) {
        DocumentContent content = DocumentContent.builder()
                .document(documentService.getRequired(command.documentId()))
                .contentRole(command.contentRole())
                .storageType(command.storageType())
                .mimeType(command.mimeType())
                .charsetName(command.charsetName())
                .textContent(command.textContent())
                .binaryContent(command.binaryContent())
                .binaryRef(command.binaryRef())
                .contentHash(command.contentHash())
                .sizeBytes(command.sizeBytes())
                .build();
        return contentRepository.save(content);
    }

    @Transactional(readOnly = true)
    public DocumentContent getRequired(UUID contentId) {
        return contentRepository.findById(contentId)
                .orElseThrow(() -> new IllegalArgumentException("Unknown content id: " + contentId));
    }

    @Transactional(readOnly = true)
    public List<DocumentContent> findByDocument(UUID documentId) {
        return contentRepository.findByDocument_Id(documentId);
    }
}
