package ru.kovbasa.tests;

import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import org.junit.jupiter.api.Test;
import ru.kovbasa.pages.PaymentPage;
import ru.kovbasa.pages.SubscriptionPage;

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

public class SubscriptionTest extends BaseTest {

    @Test
    void subscriptionFlow() {
        SubscriptionPage subscription = new SubscriptionPage(page(), config);
        subscription.open();

        Locator tiles = subscription.getSubscriptionTiles();
        tiles.first().waitFor();
        assertTrue(tiles.count() > 0, "Subscription tiles should be visible");

        Locator tile = tiles.first();

        subscription.expandDetails(tile);
        assertTrue(subscription.isDetailsExpanded(tile),
                "Details should expand after clicking 'Подробнее'");

        subscription.collapseDetails(tile);
        assertFalse(subscription.isDetailsExpanded(tile),
                "Details should collapse after clicking 'Свернуть'");

        Page paymentPage = subscription.clickBuy(tile);
        if (paymentPage.url().contains("/subscription")) {
            Locator trialCard = subscription.getTrialCard();
            trialCard.waitFor();
            String priceBefore = subscription.getPriceFromCard(tile);
            String durationBefore = subscription.getDurationFromCard(tile);

            subscription.selectTrialOnSubscription(trialCard);

            String priceAfter = subscription.getPriceFromCard(trialCard);
            String durationAfter = subscription.getDurationFromCard(trialCard);

            assertNotEquals(priceBefore, priceAfter, "Price should change for Trial");
            assertNotEquals(durationBefore, durationAfter,
                    "Duration should change for Trial");
            return;
        }

        PaymentPage payment = new PaymentPage(paymentPage);
        assertTrue(payment.isOpened(), "Payment page should be opened");

        assertTrue(payment.selectFirstNonTrial(),
                "Non-trial plan should be selectable");
        String priceBefore = payment.getPriceText();
        String durationBefore = payment.getDurationText();

        payment.selectTrial();
        payment.waitForPlanChange(priceBefore, durationBefore);

        String priceAfter = payment.getPriceText();
        String durationAfter = payment.getDurationText();

        assertNotEquals(priceBefore, priceAfter, "Price should change for Trial");
        assertNotEquals(durationBefore, durationAfter,
                "Duration should change for Trial");
    }
}
