import { expect, type Locator, type Page } from '@playwright/test';
import { InsuranceBasePage } from './InsuranceBasePage';
import { ICustomerDetails } from '@business-logic/types/CustomerDetails';

export class PolicyDriverPage extends InsuranceBasePage {
    readonly page: Page;
    readonly driverListItems: Locator;
    readonly driverNotListedOption: Locator;
    readonly vehicleParkedOption: Locator;
    url = process.env['BASE_URL']! + '/FixMyGlass/PolicyDriver.aspx';

    constructor(page: Page) {
        super(page);
        this.page = page;

        // Locators for driver list items (the clickable areas)
        this.driverListItems = this.page.locator('.list-group-item');
        // Locators for driver options
        this.driverNotListedOption = this.page.getByRole('link', { name: 'Driver not listed' });
        this.vehicleParkedOption = this.page.getByRole('link', { name: 'Vehicle was parked' });

        // this.validateURL(this.url);
    }

    async selectPolicyDriver(customerDetails: ICustomerDetails): Promise<void> {
        // Format the customer name for matching
        const customerFullName = `${customerDetails.firstName} ${customerDetails.lastName}`.toUpperCase();
        
        // Get all driver list items
        const driverItems = await this.driverListItems.all();
        let driverFound = false;
        
        // Check each driver item for a match with our customer
        for (const item of driverItems) {
            const nameText = await item.locator('.third-span').textContent();
            
            if (nameText && nameText.toUpperCase().includes(customerFullName)) {
                // If we found a match, click the list-group-item (the whole row)
                await item.click();
                driverFound = true;
                break;
            }
        }
        
        // If no match was found, select "Driver not listed"
        if (!driverFound) {
            await this.driverNotListedOption.click();
        }
    }
    
}