package dev.lions.unionflow.server.repository;

import dev.lions.unionflow.server.entity.BackupConfig;
import io.quarkus.hibernate.orm.panache.PanacheQuery;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;

@DisplayName("BackupConfigRepository — tests unitaires")
class BackupConfigRepositoryTest {

    /**
     * Sous-classe concrète permettant d'instancier et d'espionner BackupConfigRepository
     * sans CDI ni Panache réel.
     */
    static class TestableBackupConfigRepository extends BackupConfigRepository {
        // hérite de BackupConfigRepository sans contexte CDI
    }

    private BackupConfigRepository repo;

    @BeforeEach
    void setUp() {
        repo = spy(new TestableBackupConfigRepository());
    }

    @Test
    @DisplayName("classExists : le repository peut être instancié par réflexion")
    void classExists() {
        assertThat(new TestableBackupConfigRepository()).isNotNull();
    }

    @Test
    @DisplayName("getConfig : retourne Optional.empty() si aucun résultat")
    @SuppressWarnings("unchecked")
    void getConfig_noResult_returnsEmpty() {
        PanacheQuery<BackupConfig> query = mock(PanacheQuery.class);
        when(query.firstResultOptional()).thenReturn(Optional.empty());
        doReturn(query).when(repo).find(anyString());

        Optional<BackupConfig> result = repo.getConfig();

        assertThat(result).isEmpty();
    }

    @Test
    @DisplayName("getConfig : retourne Optional.of(config) si une config existe")
    @SuppressWarnings("unchecked")
    void getConfig_withResult_returnsConfig() {
        BackupConfig config = new BackupConfig();
        PanacheQuery<BackupConfig> query = mock(PanacheQuery.class);
        when(query.firstResultOptional()).thenReturn(Optional.of(config));
        doReturn(query).when(repo).find(anyString());

        Optional<BackupConfig> result = repo.getConfig();

        assertThat(result).isPresent();
        assertThat(result.get()).isSameAs(config);
    }
}
