import { expect } from "@playwright/test"

export class CheckoutPage {

    constructor(page) {
        this.page = page
        this.basketCards = page.locator('[data-qa="basket-card"]')
        this.basketItemPrices = page.locator('[data-qa="basket-item-price"]')
        this.basketItemRemoveButtons = page.locator('[data-qa="basket-card-remove-item"]')
        this.continueToCheckoutButton = page.locator('[data-qa="continue-to-checkout"]')


    }

    removeCheapestProduct = async () => {
        await this.basketCards.first().waitFor()
        await this.basketItemPrices.first().waitFor()

        const itemsBefore = await this.basketCards.count()
        const allPriceTexts = await this.basketItemPrices.allInnerTexts()
        const convertToNumbers = allPriceTexts.map((text) => {
            const formatText = text.replace("$","")
            return parseInt(formatText, 10)
        })

        const smallestPrice = Math.min(convertToNumbers)
        const smallestPriceIndex = convertToNumbers.indexOf(smallestPrice)
        const specificRemoveButton = this.basketItemRemoveButtons.nth(smallestPriceIndex)

        await specificRemoveButton.waitFor()
        await specificRemoveButton.click()

        await expect(this.basketCards).toHaveCount(itemsBefore - 1)
    }

    continueToCheckout = async () => {

        await this.continueToCheckoutButton.waitFor()
        await this.continueToCheckoutButton.click()
        await this.page.waitForURL(/\/login/, {timeout: 3000})
    }


}