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

import at.procon.dip.domain.access.DocumentVisibility;
import at.procon.dip.domain.document.DocumentFamily;
import at.procon.dip.domain.document.DocumentStatus;
import at.procon.dip.domain.document.DocumentType;
import at.procon.dip.domain.document.entity.Document;
import at.procon.dip.domain.document.repository.DocumentRepository;
import at.procon.dip.domain.document.service.DocumentService;
import at.procon.dip.domain.document.service.command.CreateDocumentCommand;
import at.procon.ted.model.entity.ProcurementDocument;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * Side-effect-free helper for TED projection flows.
 * <p>
 * Unlike the legacy Phase 2 bridge, this service only ensures that the canonical
 * DOC document root exists and is refreshed with TED metadata. It intentionally
 * does not create/update sources, contents, representations, or embeddings.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TedGenericDocumentRootService {

    private final DocumentRepository documentRepository;
    private final DocumentService documentService;

    @Transactional
    public UUID ensureGenericTedDocumentRoot(ProcurementDocument tedDocument) {
        return ensureGenericTedDocument(tedDocument).getId();
    }

    @Transactional
    public Document ensureGenericTedDocument(ProcurementDocument tedDocument) {
        Document document = documentRepository.findByDedupHash(tedDocument.getDocumentHash())
                .orElseGet(() -> createGenericDocument(tedDocument));

        document.setDocumentType(DocumentType.TED_NOTICE);
        document.setDocumentFamily(DocumentFamily.PROCUREMENT);
        document.setVisibility(DocumentVisibility.PUBLIC);
        document.setStatus(DocumentStatus.CLASSIFIED);
        document.setTitle(tedDocument.getProjectTitle());
        document.setSummary(tedDocument.getProjectDescription());
        document.setLanguageCode(tedDocument.getLanguageCode());
        document.setMimeType("application/xml");
        document.setBusinessKey(buildBusinessKey(tedDocument));
        document.setDedupHash(tedDocument.getDocumentHash());

        Document saved = documentService.save(document);
        log.debug("Ensured side-effect-free generic TED document root {} for legacy TED document {}",
                saved.getId(), tedDocument.getId());
        return saved;
    }

    private Document createGenericDocument(ProcurementDocument tedDocument) {
        return documentService.create(new CreateDocumentCommand(
                null,
                DocumentVisibility.PUBLIC,
                DocumentType.TED_NOTICE,
                DocumentFamily.PROCUREMENT,
                DocumentStatus.CLASSIFIED,
                tedDocument.getProjectTitle(),
                tedDocument.getProjectDescription(),
                tedDocument.getLanguageCode(),
                "application/xml",
                buildBusinessKey(tedDocument),
                tedDocument.getDocumentHash()
        ));
    }

    private String buildBusinessKey(ProcurementDocument tedDocument) {
        if (StringUtils.hasText(tedDocument.getPublicationId())) {
            return "TED_NOTICE:" + tedDocument.getPublicationId();
        }
        if (StringUtils.hasText(tedDocument.getNoticeId())) {
            return "TED:notice:" + tedDocument.getNoticeId();
        }
        if (StringUtils.hasText(tedDocument.getNoticeUrl())) {
            return "TED:url:" + tedDocument.getNoticeUrl();
        }
        return "TED:hash:" + tedDocument.getDocumentHash();
    }
}
