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 RbcParserServiceTest {

    @Mock
    private MarketItemRepository marketItemRepository;

    @InjectMocks
    private RbcParserService rbcParserService;

    @BeforeEach
    void setUp() {
        ReflectionTestUtils.setField(rbcParserService, "rssFeedUrl",
                "https://static.feed.rbc.ru/rbc/logical/footer/news.rss");
    }

    @Test
    void testGetRbcItemsCount() {
        // Given
        when(marketItemRepository.countBySourceName("РБК")).thenReturn(10L);

        // When
        long count = rbcParserService.getRbcItemsCount();

        // Then
        assertEquals(10L, count);
        verify(marketItemRepository).countBySourceName("РБК");
    }

    @Test
    void testGetAllRbcItems() {
        // 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 = rbcParserService.getAllRbcItems();

        // Then
        assertEquals(1, result.size());
        assertEquals("РБК", result.get(0).getSourceName());
        verify(marketItemRepository).findBySourceName("РБК");
    }

    @Test
    void testParseAndSaveRssFeed_WhenFeedIsNull() {
        // When
        List<MarketItem> result = rbcParserService.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(rbcParserService, "generateHash", url, title);
        String hash2 = (String) ReflectionTestUtils.invokeMethod(rbcParserService, "generateHash", url, title);

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