package org.raddatz.familienarchiv.tag;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.raddatz.familienarchiv.PostgresContainerConfig;
import org.raddatz.familienarchiv.config.FlywayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest;
import org.springframework.boot.jdbc.test.autoconfigure.AutoConfigureTestDatabase;
import org.springframework.context.annotation.Import;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Real-Postgres proof that {@link TagService#resolveRootTags} walks a persisted tag chain to its
 * true root through the recursive-CTE {@link TagRepository#findAncestorIds}. The CTE cannot run on
 * H2, so this uses {@code postgres:16-alpine} via Testcontainers. Exhaustive case coverage lives in
 * {@link TagServiceTest} (mocked); this pins the DB-dependent ancestry walk (issue #835, REQ-003/004).
 */
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import({PostgresContainerConfig.class, FlywayConfig.class})
class TagServiceIntegrationTest {

    @Autowired private TagRepository tagRepository;
    private TagService tagService;

    @BeforeEach
    void setUp() {
        tagService = new TagService(tagRepository);
    }

    private Tag tag(String name, String color, UUID parentId) {
        return tagRepository.save(Tag.builder().name(name).color(color).parentId(parentId).build());
    }

    @Test
    void resolveRootTags_walksPersistedChainToRoot_withRootColor() {
        // leaf → mid → root resolves to the root's (id, name, color) via the real recursive CTE.
        Tag root = tag("Krieg", "sienna", null);
        Tag mid = tag("Feldpost", null, root.getId());
        Tag leaf = tag("Briefe von der Front", null, mid.getId());

        Map<UUID, RootTag> result = tagService.resolveRootTags(List.of(leaf));

        assertThat(result.get(leaf.getId())).isEqualTo(new RootTag(root.getId(), "Krieg", "sienna"));
    }

    @Test
    void resolveRootTags_returnsRootItself_forPersistedRoot() {
        Tag root = tag("Weihnachten", "amber", null);

        Map<UUID, RootTag> result = tagService.resolveRootTags(List.of(root));

        assertThat(result.get(root.getId())).isEqualTo(new RootTag(root.getId(), "Weihnachten", "amber"));
    }
}
