package ru.kovbasa.tests;

import com.microsoft.playwright.Page;
import java.util.List;
import org.junit.jupiter.api.Test;
import ru.kovbasa.pages.CatalogPage;
import ru.kovbasa.pages.CorporatePage;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class CorporateServicesTest extends BaseTest {

    @Test
    void corporateServicesNavigation() {
        CorporatePage corporate = new CorporatePage(page(), config);
        corporate.open();

        var targetPage = corporate.clickLearnMoreInNeedCourseBlock();
        CorporatePage businessPage = targetPage == page() ? corporate
                : new CorporatePage(targetPage, config);
        assertTrue(businessPage.isBusinessCoursePageOpened(),
                "Business course development page should be opened");

        List<String> directions = businessPage.getDirections().stream()
                .map(String::trim)
                .filter(text -> !text.isBlank())
                .toList();
        assertFalse(directions.isEmpty(), "Directions should be displayed");

        CorporatePage.DirectionClick directionClick = businessPage.clickFirstDirection();
        String clickedDirection = directionClick.value();
        Page catalogPage = directionClick.page();

        boolean catalogOpened = catalogPage.url().contains("/catalog/courses")
                || catalogPage.getByText("Каталог").first().isVisible();
        assertTrue(catalogOpened, "Catalog should be opened after direction click");

        CatalogPage catalog = new CatalogPage(catalogPage, config);
        String expectedCategory = extractCategoryParam(clickedDirection);
        if (expectedCategory != null) {
            assertTrue(catalogPage.url().contains("categories=" + expectedCategory),
                    "Catalog should open with selected category from direction link");
        } else {
            boolean directionSelected = catalog.isDirectionSelected(clickedDirection);
            assertTrue(directionSelected, "Clicked direction should be selected in catalog");
        }
    }

    private String extractCategoryParam(String linkOrText) {
        if (linkOrText == null) {
            return null;
        }
        int idx = linkOrText.indexOf("categories=");
        if (idx < 0) {
            return null;
        }
        String tail = linkOrText.substring(idx + "categories=".length());
        int amp = tail.indexOf('&');
        return amp >= 0 ? tail.substring(0, amp) : tail;
    }
}
