package shop;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * The first draft, exactly as an AI agent writes it when it is handed the page source of /v1 and told
 * "write Selenium tests for this page". Nothing here was edited after the first run. Each test is repeated
 * five times because some of them depend on timing.
 */
@ExtendWith(BrowserSupport.ResultLog.class)
class AgentDraftTest {

    static ShopServer shop;
    WebDriver driver;

    @BeforeAll
    static void startShop() throws Exception { shop = new ShopServer(); }

    @BeforeEach
    void open() {
        driver = BrowserSupport.newDriver();
        driver.get(shop.url(BrowserSupport.version()));
    }

    @AfterEach
    void close() { driver.quit(); }

    @RepeatedTest(5)
    void addFirstProductShowsOneInCart() throws Exception {
        driver.findElement(By.cssSelector(".card .btn-primary")).click();
        Thread.sleep(300);
        assertEquals("1", driver.findElement(By.id("cart-count")).getText());
    }

    @RepeatedTest(5)
    void addTwoProductsShowsTwoInCart() throws Exception {
        driver.findElement(By.xpath("(//button[text()='Add to cart'])[1]")).click();
        driver.findElement(By.xpath("(//button[text()='Add to cart'])[2]")).click();
        Thread.sleep(300);
        assertEquals("2", driver.findElement(By.id("cart-count")).getText());
    }

    @RepeatedTest(5)
    void searchingForPenLeavesOneProduct() {
        driver.findElement(By.id("q")).sendKeys("Pen");
        driver.findElement(By.id("go")).click();
        long visible = driver.findElements(By.cssSelector(".card")).stream().filter(WebElement::isDisplayed).count();
        assertEquals(1, visible);
    }

    @RepeatedTest(5)
    void notebookCosts120Rupees() {
        String price = driver.findElement(By.xpath("//h3[text()='Notebook']/following-sibling::span")).getText();
        assertEquals("₹120", price);
    }

    @RepeatedTest(5)
    void addingThePenThreeTimesShowsThree() throws Exception {
        WebElement add = driver.findElement(By.cssSelector(".card:nth-child(2) .btn-primary"));
        add.click();
        add.click();
        add.click();
        Thread.sleep(300);
        assertEquals("3", driver.findElement(By.id("cart-count")).getText());
    }

    @RepeatedTest(5)
    void emptySearchShowsAllThreeProducts() {
        assertEquals(3, driver.findElements(By.className("card")).size());
    }
}
