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

    @Mock
    private MarketItemRepository marketItemRepository;

    @InjectMocks
    private LsmParserService lsmParserService;

    @BeforeEach
    void setUp() {
        ReflectionTestUtils.setField(lsmParserService, "rssFeedUrl", "https://lsm.kz/rss");
    }

    @Test
    void testGetLsmItemsCount() {
        // Given
        when(marketItemRepository.countBySourceName("LSM.kz")).thenReturn(5L);

        // When
        long count = lsmParserService.getLsmItemsCount();

        // Then
        assertEquals(5L, count);
        verify(marketItemRepository).countBySourceName("LSM.kz");
    }

    @Test
    void testGetAllLsmItems() {
        // Given
        List<MarketItem> mockItems = new ArrayList<>();
        MarketItem item1 = new MarketItem();
        item1.setSourceName("LSM.kz");
        item1.setTitle("Test News 1");
        mockItems.add(item1);

        when(marketItemRepository.findBySourceName("LSM.kz")).thenReturn(mockItems);

        // When
        List<MarketItem> result = lsmParserService.getAllLsmItems();

        // Then
        assertEquals(1, result.size());
        assertEquals("LSM.kz", result.get(0).getSourceName());
        verify(marketItemRepository).findBySourceName("LSM.kz");
    }

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

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