package at.procon.dip.ingestion.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import at.procon.dip.domain.access.DocumentAccessContext;
import at.procon.dip.domain.document.entity.Document;
import at.procon.dip.domain.document.service.DocumentRelationService;
import at.procon.dip.ingestion.config.DipIngestionProperties;
import at.procon.dip.ingestion.dto.ImportedDocumentResult;
import at.procon.dip.ingestion.service.TedPackageExpansionService.TedPackageEntry;
import at.procon.dip.ingestion.spi.SourceDescriptor;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class TedPackageChildImportProcessorTest {

    @Mock
    private GenericDocumentImportService importService;
    @Mock
    private DocumentRelationService relationService;

    private DipIngestionProperties properties;
    private TedPackageChildImportProcessor processor;

    @BeforeEach
    void setUp() {
        properties = new DipIngestionProperties();
        properties.setTedPackageImportBatchId("ted-batch");
        processor = new TedPackageChildImportProcessor(importService, relationService, properties);
    }

    @Test
    void shouldMarkTedPackageChildrenForDeferredLexicalIndexingWhenEnabled() {
        properties.setTedPackageDeferLexicalIndexing(true);
        when(importService.importDocument(any())).thenReturn(new ImportedDocumentResult(
                Document.builder().id(UUID.randomUUID()).build(),
                null,
                List.of(),
                false
        ));

        processor.processChild(
                UUID.randomUUID(),
                "PKG-1",
                OffsetDateTime.now(),
                DocumentAccessContext.publicDocument(),
                new TedPackageEntry("notice-1.xml", "path/notice-1.xml", "<xml/>".getBytes(StandardCharsets.UTF_8), "<xml/>"),
                1
        );

        ArgumentCaptor<SourceDescriptor> captor = ArgumentCaptor.forClass(SourceDescriptor.class);
        verify(importService).importDocument(captor.capture());
        assertThat(captor.getValue().attributes()).containsEntry(IngestionInternalAttributes.DEFER_LEXICAL_INDEX, "true");
    }
}
