package kz.konturai.parser.service;

import kz.konturai.parser.model.MarketItem;
import kz.konturai.parser.repository.MarketItemRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.util.ReflectionTestUtils;

import java.util.ArrayList;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class VedomostiParserServiceTest {

    @Mock
    private MarketItemRepository marketItemRepository;

    @InjectMocks
    private VedomostiParserService vedomostiParserService;

    @BeforeEach
    void setUp() {
        ReflectionTestUtils.setField(vedomostiParserService, "rssFeedUrl",
                "https://www.vedomosti.ru/rss/rubric/technology/internet");
    }

    @Test
    void testGetVedomostiItemsCount() {
        // Given
        when(marketItemRepository.countBySourceName("Ведомости")).thenReturn(15L);

        // When
        long count = vedomostiParserService.getVedomostiItemsCount();

        // Then
        assertEquals(15L, count);
        verify(marketItemRepository).countBySourceName("Ведомости");
    }

    @Test
    void testGetAllVedomostiItems() {
        // Given
        List<MarketItem> mockItems = new ArrayList<>();
        MarketItem item1 = new MarketItem();
        item1.setSourceName("Ведомости");
        item1.setTitle("Test News 1");
        mockItems.add(item1);

        when(marketItemRepository.findBySourceName("Ведомости")).thenReturn(mockItems);

        // When
        List<MarketItem> result = vedomostiParserService.getAllVedomostiItems();

        // Then
        assertEquals(1, result.size());
        assertEquals("Ведомости", result.get(0).getSourceName());
        verify(marketItemRepository).findBySourceName("Ведомости");
    }

    @Test
    void testParseAndSaveRssFeed_WhenFeedIsNull() {
        // When
        List<MarketItem> result = vedomostiParserService.parseAndSaveRssFeed();

        // Then
        assertNotNull(result);
        assertTrue(result.isEmpty());
    }

    @Test
    void testGenerateHash() throws Exception {
        // Given
        String url = "https://example.com/news/1";
        String title = "Test News";

        // When
        String hash1 = (String) ReflectionTestUtils.invokeMethod(vedomostiParserService, "generateHash", url, title);
        String hash2 = (String) ReflectionTestUtils.invokeMethod(vedomostiParserService, "generateHash", url, title);

        // Then
        assertNotNull(hash1);
        assertNotNull(hash2);
        assertEquals(hash1, hash2); // Same input should produce same hash
        assertNotEquals(hash1, (String) ReflectionTestUtils.invokeMethod(vedomostiParserService, "generateHash", url,
                "Different Title"));
    }
}
