import TestCase from "@business-logic/types/TestCase";
import { expect, Page } from "@playwright/test";
import { addSmokeTagToRandomTest, prepareTest, test, TestInfo } from "@business-logic/types/Test";
import { RuleEngine, ValidationOptions } from "@business-logic/types/RuleEngine";
import { ICustomerDetails } from "@business-logic/types/CustomerDetails";
import essentialHpTestCases from "./0016_EssentialRepairInShop";
import essentialReplaceTestCases from "./0013_EssentialReplace";
import { BailoutCode, VehicleDamage, VehicleLookupType } from "@business-logic/types/Enums";
import essentialTpaNotEnabledTestCases from "./0003_EssentialTpaNotEnabledBailout";
import essentialDoNotSeeShopTestCases from "./0011_EssentialDoNotSeeShopBailout";
import essentialVehicleNotFoundTestCases from "./0010_EssentialVehicleNotFoundBailout";
import essentialPartsServiceErrorBailout_0009 from "./0009_EssentialPartsServiceErrorBailout";
import essentialRepairMobileTests from "./0014_EssentialRepairMobile";
import essentialReplacePartsQuestionsDropoff_0015 from "./0015_EssentialReplacePartsQuestionsDropoff";
import essentialUniqueGlassTests from "./0012_EssentialUniqueGlass";
import essentialRepairInShopAcuraTests from "./0002_EssentialRepairInShopAcura";
import essentialTpaEnabled_0004 from "./0004_EssentialTpaEnabled";
import essentialRepairMobileHyundaiTests from "./0007_EssentialRepairHyundaiMobile";
import essentialTpaNotEnabledReplace_0017 from "./0017_EssentialTpaNotEnabledBailoutReplace";
import essentialTpaEnabledReplace_0018 from "./0018_EssentialTpaEnabledReplace";
import essentialTpaEnabledReplaceRecal_0019 from "./0019_EssentialTpaEnabledReplaceRecal";
import advancedScenario0001TestCases from "./advanced/0001a_ReplaceInShopCredit";
import advancedScenario0003TestCases from "./advanced/0003a_MobileAfterpay";
import essentialReplaceDynamicAdasTests from "./0005_EssentialReplaceDynamicAdas";
import essentialReplaceStaticAdasTests from "./0001_EssentialReplaceStatisAdas";
import essentialVehicleLookupBailoutTests from "./0020_EssentialVehicleLookupBailout";
import essentialPriceServiceErrorBailoutTests from "./0021_EssentialPriceServiceErrorBailout";
import essentialServiceableBigTruckTestCases from "./0022_EssentialServiceableBigTruck";
import essentialNonServiceableBigTruckTestCases from "./0023_EssentialNonServiceableBigTruck";
import essentialNonServiceableBigTruckVinTestCases from "./0024_EssentialNonServiceableBigTruckVin";
import { forceAPIError, mockApiManager } from "@impl/utils/HttpUtils";

import advancedScenario0002TestCases from "./advanced/0002a_ReplaceOemEndorsement";
import ApiResponseInterceptUtil from "@impl/api/ApiResponseInterceptUtil";
import advancedScenario0004aTestCases from "./advanced/0004a_NoDeductibleAdas";
import advancedScenario0006TestCases from "./advanced/0006a_RepairNoDeductibleMobile";
import advancedScenario0007TestCases from "./advanced/0007a_RepairStateLanguage";
import advancedScenario0008TestCases from "./advanced/0008a_RepairTpa";
import advancedScenario0011TestCases from "./advanced/0011a_ItacNoAdas";
import advancedScenario0012TestCases from "./advanced/0012a_ItacDropOff";
import advancedScenario0014TestCases from "./advanced/0014a_NoCompAdas";
import advancedScenario0013TestCases from "./advanced/0013a_ItacMobile";
import advancedScenario0015TestCases from "./advanced/0015a_NoCompPartQuestions";
import advancedScenario0016TestCases from "./advanced/0016a_NoCompAllGlass";
import advancedScenario0017TestCases from "./advanced/0017a_NoCompPremium";
import advancedScenario0018TestCases from "./advanced/0018a_NoCompGlassOnly";
import advancedScenario0019TestCases from "./advanced/0019a_NoCompEditVehicle";
import advancedScenario0020TestCases from "./advanced/0020a_NoCompChangeLoc";
import advancedScenario0005TestCases from "./advanced/0005a_CapabilityQuestions";
import advancedScenario0009TestCases from "./advanced/0009a_NoDeductibleFlorida";
import advancedScenario0010TestCases from "./advanced/0010a_RearGlass";
import advancedScenario0021TestCases from "./advanced/0021a_VehicleByPlate";
import advancedScenario0022TestCases from "./advanced/0022a_VehicleByVIN";
import advancedScenario0023TestCases from "./advanced/0023a_VehicleByVINPartsQns";
import { createAccessibilityHtmlReport } from "@impl/utils/ReportUtils";
import advancedScenario0024TestCases from "./advanced/0024a_VehicleByVINUnverifiedBailout";
import advancedScenario0025TestCases from "./advanced/0025a_VehicleByVINUnverifiedBailout";
import advancedScenario0026aTestCases from "./advanced/0026a_NoDeductibleAdasBailout5";
import advancedScenario0028aTestCases from "./advanced/0028a_ItacCancelMyClaim";
import advancedScenario0029aTestCases from "./advanced/0029a_HeavyVehicleBailout";
import advancedScenario0030aTestCases from "./advanced/0030a_PartsServiceBailout";
import advancedScenario0031aTestCases from "./advanced/0031a_ReplaceServiceableBigTruck";
import advancedScenario0032aTestCases from "./advanced/0032a_DeclineNonServiceableBigTruck";



test.describe.parallel('ISS QA Automation Regression', () => {
    const ruleEngine = new RuleEngine<TestCase>();
    const options = new ValidationOptions();
    //TODO: Add new tests
    addSmokeTagToRandomTest(essentialReplaceStaticAdasTests);
    addSmokeTagToRandomTest(essentialRepairInShopAcuraTests);
    addSmokeTagToRandomTest(essentialTpaNotEnabledTestCases);
    addSmokeTagToRandomTest(essentialTpaEnabled_0004);
    addSmokeTagToRandomTest(essentialReplaceDynamicAdasTests);
    addSmokeTagToRandomTest(essentialRepairMobileHyundaiTests);
    addSmokeTagToRandomTest(essentialVehicleNotFoundTestCases);
    addSmokeTagToRandomTest(essentialPartsServiceErrorBailout_0009);
    addSmokeTagToRandomTest(essentialDoNotSeeShopTestCases);
    addSmokeTagToRandomTest(essentialUniqueGlassTests);
    addSmokeTagToRandomTest(essentialReplaceTestCases);
    addSmokeTagToRandomTest(essentialRepairMobileTests);
    addSmokeTagToRandomTest(essentialReplacePartsQuestionsDropoff_0015);
    addSmokeTagToRandomTest(essentialHpTestCases);
    addSmokeTagToRandomTest(essentialTpaNotEnabledReplace_0017);
    addSmokeTagToRandomTest(essentialTpaEnabledReplace_0018);
    addSmokeTagToRandomTest(essentialTpaEnabledReplaceRecal_0019);
    addSmokeTagToRandomTest(essentialVehicleLookupBailoutTests);
    addSmokeTagToRandomTest(essentialPriceServiceErrorBailoutTests);
    addSmokeTagToRandomTest(essentialServiceableBigTruckTestCases);
    addSmokeTagToRandomTest(essentialNonServiceableBigTruckTestCases);
    addSmokeTagToRandomTest(essentialNonServiceableBigTruckVinTestCases);

    //Scenario 1
    for (const testCase of essentialReplaceStaticAdasTests) {

        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 2
    for (const testCase of essentialRepairInShopAcuraTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 3
    for (const testCase of essentialTpaNotEnabledTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 4
    for (const testCase of essentialTpaEnabled_0004) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 5
    for (const testCase of essentialReplaceDynamicAdasTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 7
    for (const testCase of essentialRepairMobileHyundaiTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 9
    for (const testCase of essentialPartsServiceErrorBailout_0009) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 10
    for (const testCase of essentialVehicleNotFoundTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 11
    for (const testCase of essentialDoNotSeeShopTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 12
    for (const testCase of essentialUniqueGlassTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 13 //defect# SSR-2009
    for (const testCase of essentialReplaceTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 14
    for (const testCase of essentialRepairMobileTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 15
    for (const testCase of essentialReplacePartsQuestionsDropoff_0015) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 16
    for (const testCase of essentialHpTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 17
    for (const testCase of essentialTpaNotEnabledReplace_0017) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 18
    for (const testCase of essentialTpaEnabledReplace_0018) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 19
    for (const testCase of essentialTpaEnabledReplaceRecal_0019) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 20
    for (const testCase of essentialVehicleLookupBailoutTests) {
        test(...prepareTest(testCase, run, options, ruleEngine)); //skipping this until SSR-2004 is fixed
    }
    //Scenario 21
    for (const testCase of essentialPriceServiceErrorBailoutTests) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 22
    for (const testCase of essentialServiceableBigTruckTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    //Scenario 23
    for (const testCase of essentialNonServiceableBigTruckTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    // Scenario 24
    for (const testCase of essentialNonServiceableBigTruckVinTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    


    // Advanced Scenarios

    // Scenario 0001a
    for (const testCase of advancedScenario0001TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0002a
    for (const testCase of advancedScenario0002TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0003a
    // Note: payment will fail in dev. Payment (PIA) works fine in SYS
    for (const testCase of advancedScenario0003TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0004a
    for (const testCase of advancedScenario0004aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0005a
    for (const testCase of advancedScenario0005TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0006a
    for (const testCase of advancedScenario0006TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0007a
    for (const testCase of advancedScenario0007TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0008a
    for (const testCase of advancedScenario0008TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0009a
    for (const testCase of advancedScenario0009TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
    // Scenario 0010a
    for (const testCase of advancedScenario0010TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0011a
    for (const testCase of advancedScenario0011TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0012a
    for (const testCase of advancedScenario0012TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0013a
    for (const testCase of advancedScenario0013TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0014a
    for (const testCase of advancedScenario0014TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0015a
    for (const testCase of advancedScenario0015TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0016a
    // FIXME: Defect was created INSR-2138
    for (const testCase of advancedScenario0016TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0017a
    for (const testCase of advancedScenario0017TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0018a
    for (const testCase of advancedScenario0018TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0019a
    for (const testCase of advancedScenario0019TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0020a : There's a defect open INSR-2149
    for (const testCase of advancedScenario0020TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0021a
    for (const testCase of advancedScenario0021TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0022a
    for (const testCase of advancedScenario0022TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0023a
    for (const testCase of advancedScenario0023TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0024a
    for (const testCase of advancedScenario0024TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0025a
    for (const testCase of advancedScenario0025TestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0026a
    for (const testCase of advancedScenario0026aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0028a
    for (const testCase of advancedScenario0028aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0029a
    for (const testCase of advancedScenario0029aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0030a
    for (const testCase of advancedScenario0030aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0031a
    for (const testCase of advancedScenario0031aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }

    // Scenario 0032a
    for (const testCase of advancedScenario0032aTestCases) {
        test(...prepareTest(testCase, run, options, ruleEngine));
    }
});


test.afterEach(async ({ page, testInfo }) => {
    await TestCase.afterEachMethod(page, testInfo);
});

test.afterAll(() => {
    createAccessibilityHtmlReport();
});

async function run(page: Page, testInfo: TestInfo): Promise<void> {
    if (!(testInfo.testCase.testData?.isMockTesting ?? false)) {
        if (testInfo.testCase.testData?.isPolicyFound) {
            await testInfo.testCase.setup();
        }
    }
    testInfo.testCase.setupPages(page);
    if (testInfo.testCase.testData.isAuthenticationRequired) {
        await testInfo.testCase.pages.welcomePage.gotoWithAuthentication(testInfo.testCase.testData!.clientTag!);
    }
    else {
        await testInfo.testCase.pages.welcomePage.goto(testInfo.testCase.testData!.clientTag!);
    }
    await runWorkflow(page, testInfo.testCase);
}

async function runWorkflow(page: Page, testCase: TestCase) {
    if (testCase.testData?.isMockTesting ?? false) {
        // await mockApiManager.mockApiResponse(page, 'common', testCase.testData!.isMockTesting ?? false);
        await mockApiManager.mockApiResponse(page, testCase.name.split(':')[0], testCase.testData!.isMockTesting ?? false);

    } else {
        // Intercept API Responses
        const apiResponseInterceptUtil = new ApiResponseInterceptUtil(testCase.testData);
        page.on('response', apiResponseInterceptUtil.handleInterceptResponse);
        await mockApiManager.mockApiResponse(page, 'common', true); // making sure no experiments
    }

    // Destructure data for easy access
    const { customerDetails, claimDetails, vehicleDetails, vehicleDamage,
        appointmentDetails, isSafelite, endorsements,
        partQuestions, paymentDetails, isNoComp, isItac, isRecalNotification,
        isRecalWarning, servicePackage, hasStateLawPopup, otherVehiclesOnPolicy,
        isSeparateApptsWarning, vehiclePartQuestions, editVehicleDetails, isAddressLookupValidations,
        hasMilitaryWarning, capabilityQuestions, isUseVehicleOnPolicy,
        isVehicleLookupValidations, isMoldingQuestion, isNonServiceable, isNonServiceableVin } = testCase.testData;

    let { isPolicyFound } = testCase.testData;  // Allow isPolicyFound to be re-assigned

    // Destructure pages for easy access
    const { welcomePage, duplicateCheckPage, policyHolderDetailsPage,
        vehicleSelectionPage, vehicleDamagePage, coverageStatementPage,
        providerPreferencePage, serviceLocationPage, servicePackagesPage,
        schedulePage, contactDetailsPage, orderConfirmationPage, policyVehiclesPage,
        endorsementsPage, vehicleLookupPage, partQuestionsPage, paymentMethodPage,
        vehicleLookupAddressPage, vehicleLookupLicensePage, vinLookupPage,
        bailoutPage, tpaSearchPage, tpaSubmitPage, tpaConfirmationPage,
        vehiclePartQuestionsPage, capabilityQuestionsPage, moldingQuestionsPage, addressLookupPage } = testCase.pages;

    // Destructure bailout flags
    const { isVehicleSelectBailout, isDoNotSeeMyShopBailout, isTpaNotEnabledBailout,
        isPartsServiceErrorBailout, isVehicleLookupBailout, isPriceServiceErrorBailout,
        isRequestCallbackBailout } = testCase.testData.bailoutFlags || {};

    const repairTypes: VehicleDamage[] = [
        VehicleDamage.WindshieldOneChip,
        VehicleDamage.WindshieldTwoChips,
        VehicleDamage.WindshieldThreeChips
    ]

    // Are we replacing or repairing?
    const isReplace = !repairTypes.some(damageType => {
        return vehicleDamage!.includes(damageType);
    });

    const hasEndorsements = endorsements && endorsements.length > 0;

    await test.step('WelcomePage >> Populate Customer Details', async () => {
        await welcomePage.populatePage(customerDetails!, claimDetails!, await welcomePage.hasCityInfo());
        await welcomePage.nextPage();
    });

    if (testCase.testData.isDuplicateClaim) {
        // TODO: Scenarios where we want to resume from duplicate
        // TODO: Dynamic for when we don't care if duplicate page appears

        await test.step('DuplicateCheckPage >> Start New Claim', async () => {
            await duplicateCheckPage.validateURL(duplicateCheckPage.issPageValue);
            await duplicateCheckPage.startNewClaim();
            await duplicateCheckPage.nextPage();
        });
    }

    if (isPolicyFound) {
        await test.step('PolicyVehiclesPage >> Select vehicle', async () => {
            await policyVehiclesPage.validateURL(policyVehiclesPage.issPageValue);
            await policyVehiclesPage.logReferralNumber();
            // Validate other vehicles on policy
            if (otherVehiclesOnPolicy && otherVehiclesOnPolicy.length > 0) {
                for (const vehicle of otherVehiclesOnPolicy) {
                    await policyVehiclesPage.validateVehicleIsOnPolicy(vehicle);
                }
            }
            if (!(isUseVehicleOnPolicy ?? true)) {
                await policyVehiclesPage.selectVehicleNotListed();
                await policyVehiclesPage.nextPage();
                await vehicleSelectionPage.selectVehicle(vehicleDetails!);
                await policyVehiclesPage.nextPage();
            } else {
                // Select vehicle
                await policyVehiclesPage.selectVehicle(vehicleDetails!);
                if (isNonServiceable) {
                    await policyVehiclesPage.assertNonServiceableAlertBehavior();
                    return;
                }
                await policyVehiclesPage.nextPage();
            }
        });

        if (isNonServiceable) {
            return;
        }

        if (hasEndorsements) {
            await test.step('EndorsementsPage >> Select Endorsements', async () => {
                await endorsementsPage.validateURL(endorsementsPage.issPageValue);
                await endorsementsPage.verifyEndorsements(endorsements);
                await endorsementsPage.selectEndorsements(endorsements);
                await endorsementsPage.nextPage();
            });
        }

    } else {
        await policyVehiclesPage.logReferralNumber();
        await test.step('PolicyHolderDetailsPage >> Enter customer data', async () => {
            await policyHolderDetailsPage.validateURL(policyHolderDetailsPage.issPageValue);
            await policyHolderDetailsPage.fillCustomerDetails(customerDetails!);
            await policyHolderDetailsPage.nextPage();
        });

        if (isVehicleLookupBailout) {
            forceAPIError(page, '/vehicle/api/v1/vehicle/lookup')
        }

        await test.step('VehicleDetailsPage >> Select Vehicle', async () => {
            await vehicleSelectionPage.validateURL(vehicleSelectionPage.issPageValue);
            await vehicleSelectionPage.selectVehicle(vehicleDetails!);
            if (isNonServiceable) {
                await vehicleSelectionPage.assertNonServiceableAlertBehavior();
                return;
            }
            await vehicleSelectionPage.nextPage();
        });

        if (isNonServiceable) {
            return;
        }

        if (isVehicleLookupBailout) {
            await test.step('BailoutPage >> Vehicle Lookup Bailout', async () => {
                await bailoutPage.validateURL(bailoutPage.issPageValue);
                await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.VehicleYMMSLookupError);
            });
            return;
        }
    }

    if (editVehicleDetails) {
        isPolicyFound = false;    // Flow proceeds as unverified
        testCase.testData.isPolicyFound = false;
        await test.step('VehicleDamagePage >> Click Edit Vehicle', async () => {
            await vehicleDamagePage.validateURL(vehicleDamagePage.issPageValue);
            await vehicleDamagePage.editVehicleButton.click();
        });

        await test.step('VehicleDetailsPage >> Select edited vehicle', async () => {
            await test.step('VehicleDetailsPage >> Select Vehicle', async () => {
                await vehicleSelectionPage.validateURL(vehicleSelectionPage.issPageValue);
                await vehicleSelectionPage.selectVehicle(editVehicleDetails);
                await vehicleSelectionPage.nextPage();
            });
        });
    }

    await test.step('VehicleDamagePage >> Select Damage', async () => {
        await vehicleDamagePage.validateURL(vehicleDamagePage.issPageValue);
        if (isSeparateApptsWarning) {
            await vehicleDamagePage.checkSeparateApptsWarning();
        }
        await vehicleDamagePage.selectDamage(vehicleDamage!);
        await vehicleDamagePage.nextPage();
    });

    if (isPartsServiceErrorBailout) {
        await test.step('VehicleLookupPage >> Select Lookup Type', async () => {
            await vehicleLookupPage.validateURL(vehicleLookupPage.issPageValue);
            await vehicleLookupPage.vehicleLookup(vehicleDetails!);
        });
        await test.step('VinLookupPage >> Lookup by VIN', async () => {
            await vinLookupPage.validateURL(vinLookupPage.issPageValue);
            await vinLookupPage.enterVin(vehicleDetails!.vin!);
            forceAPIError(page, '/parts/api/v1/parts')
            await vinLookupPage.nextPage();
        });
        await test.step('BailoutPage >> Parts Service Error Bailout', async () => {
            await bailoutPage.validateURL(bailoutPage.issPageValue);
            await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.PartsServiceError);
            return;
        });
        return;
    }

    if (isReplace && (!(isPolicyFound) || !(isUseVehicleOnPolicy ?? true))) {


        await test.step('VehicleLookupPage >> Select Lookup Type' + vehicleDetails?.vehicleLookupType, async () => {
            await vehicleLookupPage.validateURL(vehicleLookupPage.issPageValue);
            await vehicleLookupPage.vehicleLookup(vehicleDetails!);
        });


        if (isVehicleSelectBailout) {
            await vinLookupPage.validateURL(vinLookupPage.issPageValue);
            await test.step('Lookup vehicle  >> By VIN-' + vehicleDetails!.vin!, async () => {
                await vinLookupPage.enterVin(vehicleDetails!.vin!);
            });

            await test.step('Click Invalid vin Link', async () => {
                await vinLookupPage.triggerBailout();
            });

            await test.step('BailoutPage >> Validate Bailout-' + BailoutCode.VehicleNotFound, async () => {
                await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.VehicleNotFound);
            });

            return;
        }
        switch (vehicleDetails!.vehicleLookupType!) {
            case VehicleLookupType.Address:
                if (isAddressLookupValidations) {
                    await test.step('Address Lookup validations >> Vehicle Lookup by address: ' + customerDetails!.address.street, async () => {
                        if (Array.isArray(vehicleDetails?.address)) {
                            await addressLookupPage.validateURL(addressLookupPage.issPageValue);
                            await addressLookupPage.validateAddressLookupAlerts(vehicleDetails?.address);
                            await addressLookupPage.nextPage();
                        }
                    });
                } else {
                    await test.step('VehicleLookupAddressPage >> Lookup by address: ' + customerDetails!.address.street, async () => {
                        await vehicleLookupAddressPage.validateURL(vehicleLookupAddressPage.issPageValue);
                        await vehicleLookupAddressPage.lookupVehicleByAddress(customerDetails!, vehicleDetails!);
                        await vehicleLookupAddressPage.nextPage();
                    });
                }
                break;
            case VehicleLookupType.LicensePlateNumber:
                await vehicleLookupLicensePage.validateURL(vehicleLookupLicensePage.issPageValue);
                if (isVehicleLookupValidations) {
                    await test.step('VehicleLookupLicensePage >> Lookup by license plate: ' + vehicleDetails!.licensePlateNumber, async () => {
                        await vehicleLookupLicensePage.enterPlateDetails(vehicleDetails!, isVehicleLookupValidations);
                        await vehicleLookupLicensePage.nextPage();
                    });

                } else {
                    await test.step('VehicleLookupLicensePage >> Lookup by license plate: ' + vehicleDetails!.licensePlateNumber, async () => {
                        await vehicleLookupLicensePage.enterPlateDetails(vehicleDetails!);
                        await vehicleLookupLicensePage.nextPage();
                    });
                }
                break;
            case VehicleLookupType.Vin:
                await test.step('VinLookupPage >> Lookup by VIN: ' + vehicleDetails!.vin!, async () => {
                    await vinLookupPage.validateURL(vinLookupPage.issPageValue);
                    await vinLookupPage.enterVin(vehicleDetails!.vin!, isVehicleLookupValidations);
                    if (isNonServiceableVin) {
                        await vinLookupPage.handleNonServiceableVin();
                        return;
                    }
                    await vinLookupPage.nextPage();
                });
                if (isNonServiceableVin) {
                    return;
                }
                break;
        }
    }
    if (isMoldingQuestion) {
        await test.step('Molding Questions Page >> Select Yes', async () => {
            await moldingQuestionsPage.validateURL(moldingQuestionsPage.issPageValue);
            if (!moldingQuestionsPage) {
                console.error("moldingQuestionsPage is not initialized");
            }
            await moldingQuestionsPage.answerYes();
            await moldingQuestionsPage.nextPage();
        });
    }
    if (capabilityQuestions && capabilityQuestions.length > 0) {
        await capabilityQuestionsPage.validateURL(capabilityQuestionsPage.issPageValue);
        await capabilityQuestionsPage.validatePartQuestions(capabilityQuestions);
        await capabilityQuestionsPage.selectPartQuestionResponses(capabilityQuestions);
        await capabilityQuestionsPage.nextPage();
    }

    if (partQuestions && partQuestions.length > 0) {
        await partQuestionsPage.validateURL(partQuestionsPage.issPageValue);
        await partQuestionsPage.validatePartQuestions(partQuestions);
        await partQuestionsPage.selectPartQuestionResponses(partQuestions);
        await partQuestionsPage.nextPage();
    }

    if (vehiclePartQuestions && vehiclePartQuestions.length > 0) {
        await vehiclePartQuestionsPage.validateURL(vehiclePartQuestionsPage.issPageValue);
        await vehiclePartQuestionsPage.validatePartQuestions(vehiclePartQuestions);
        await vehiclePartQuestionsPage.selectPartQuestionResponses(vehiclePartQuestions);
        await vehiclePartQuestionsPage.nextPage();
    }
    if (isRequestCallbackBailout) {
        await test.step('CoverageStatementPage >> Cancel My claim', async () => {
            await coverageStatementPage.validateURL(coverageStatementPage.issPageValue);
            await coverageStatementPage.cancelMyClaim();
        });

        await test.step('BailoutPage >> Request Callback Bailout', async () => {
            await bailoutPage.validateURL(bailoutPage.issPageValue);
            await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.RequestCallback);            
        });
        return;
    }
    await test.step('CoverageStatementPage >> Next page', async () => {
        await coverageStatementPage.validateURL(coverageStatementPage.issPageValue);
        // Confirm no coverage
        if (isPolicyFound && (isItac || isNoComp)) {
            await coverageStatementPage.continueToScheduleButton.click();
        }

        await coverageStatementPage.nextPage();
    });

    if (hasStateLawPopup) {
        await test.step('ProviderPreferencePage >> Dismiss state law popup', async () => {
            await providerPreferencePage.validateURL(providerPreferencePage.issPageValue);
            await providerPreferencePage.validateStateLawModalIsVisible();
            await providerPreferencePage.gotItButton.click();
        });
    }

    if (!isPolicyFound || !(isItac || isNoComp)) {
        await test.step('ProviderPreferencePage >> Select Provider ' + isSafelite ? "Safelite" : "Other shops(Non-Safelite)", async () => {
            await providerPreferencePage.validateURL(providerPreferencePage.issPageValue);
            await providerPreferencePage.selectProvider(isSafelite);
        });
    }

    // validations for Recal warning mesage
    if (isRecalWarning) {
        await serviceLocationPage.validateURL(serviceLocationPage.issPageValue);
        await serviceLocationPage.validateRecalWarning();
    }

    // if isRecalNotifidation flag true additional step to acknowledge Recal notification.
    if (isRecalNotification) {
        await providerPreferencePage.validateURL(providerPreferencePage.issPageValue);
        await providerPreferencePage.acknowledgeRecalNotificaiton();
    }
    // If No-Comp or ITAC, ProviderPreferencePage does not appear
    if (!isPolicyFound || !(isItac || isNoComp)) {


        if (!isSafelite) {
            if (testCase.testData!.clientTag == '05CC1609-3631-4044-B45A-E78E13343B9A') { // Avoiding TPA flow for Federated Insureance due to Defect# SSR-1984 //Temporary fix until Defect# SSR-1984 is addressed.
                await test.step('***** Performing Safelite flow for Federal Insurance due to defec# SSR-1984 *****', async () => { });
                await test.step('TpaSearchPage >> TPA Search', async () => {
                    await tpaSearchPage.validateURL(tpaSearchPage.issPageValue);
                    await tpaSearchPage.selectFirstLocation();
                    // await tpaSearchPage.nextPage();                                  
                });
                return;
            }
            if (isTpaNotEnabledBailout) {
                await test.step('validateBailoutDetails >> Bailout code : ' + BailoutCode.TPANotEnabled, async () => {
                    await bailoutPage.validateURL(bailoutPage.issPageValue);
                    await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.TPANotEnabled);
                    return;
                });
                return;
            }

            if (isDoNotSeeMyShopBailout) {
                await test.step('TpaSearchPage >> Select "Do Not See My Shop"', async () => {
                    await tpaSearchPage.validateURL(tpaSearchPage.issPageValue);
                    await tpaSearchPage.selectDoNotSeeMyShop();
                });
                await bailoutPage.validateURL(bailoutPage.issPageValue);
                await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.DoNotSeeMyShop);
                return;
            }

            await test.step('TpaSearchPage >> TPA Search', async () => {
                await tpaSearchPage.validateURL(tpaSearchPage.issPageValue);
                await tpaSearchPage.selectFirstLocation();
                await tpaSearchPage.nextPage();
            });

            await test.step('TpaSubmitPage >> TPA Submit', async () => {
                // TODO: Validations
                await tpaSubmitPage.validateURL(tpaSubmitPage.issPageValue);
                await tpaSubmitPage.nextPage();
            });

            await test.step('TpaConfirmationPage >> TPA Confirmation', async () => {
                await tpaConfirmationPage.validateURL(tpaConfirmationPage.issPageValue);
                await tpaConfirmationPage.validateSuccessMessage();
                return;
            });
            return;
        }
    }

    await test.step('ServiceLocationPage >> Select service location', async () => {
        await serviceLocationPage.validateURL(serviceLocationPage.issPageValue);
        await serviceLocationPage.selectLocation(appointmentDetails!);
        if (hasMilitaryWarning) {
            await expect.soft(serviceLocationPage.militaryWarningMessage).toBeVisible();
        }
        await serviceLocationPage.nextPage();
    });

    await test.step('SchedulePage >> Select day and time', async () => {
        await schedulePage.validateURL(schedulePage.issPageValue);
        customerDetails!.apptDate = await schedulePage.scheduleFirstAppointment(appointmentDetails!.serviceLocation);
    });

    await test.step('ContactDetailsPage >> Validate contact details', async () => {
        const expectedContactDetails: Partial<ICustomerDetails> = {
            firstName: customerDetails!.firstName,
            lastName: customerDetails!.lastName,
            email: customerDetails!.email,
            phoneNumber: customerDetails!.phoneNumber
        };
        await contactDetailsPage.validateURL(contactDetailsPage.issPageValue);
        const actualContactDetails = await contactDetailsPage.getContactDetails();
        expect.soft(actualContactDetails).toEqual(expectedContactDetails);

        await contactDetailsPage.fillNotes(customerDetails!.notes);

        if (isPriceServiceErrorBailout) {
            forceAPIError(page, '/price/api/v1/price/combined-quote');
        }

        await contactDetailsPage.nextPage();
    });

    if (isPriceServiceErrorBailout) {
        await test.step('BailoutPage >> Price Service Error Bailout', async () => {
            await bailoutPage.validateURL(bailoutPage.issPageValue);
            await bailoutPage.validateBailoutDetails(customerDetails!, BailoutCode.PricingResponseError);
        });
        return;
    }

    await test.step('ServicePackagesPage >> Choose service package', async () => {
        await servicePackagesPage.validateURL(servicePackagesPage.issPageValue);
        customerDetails!.packagePrice = await servicePackagesPage.selectServicePackage(servicePackage!);
        await servicePackagesPage.nextPage();
    });

    if (isPolicyFound && (isUseVehicleOnPolicy ?? true) && claimDetails!.policyDeductible > 0) {
        await test.step('PaymentMethodPage >> Execute Payment', async () => {
            await paymentMethodPage.validateURL(paymentMethodPage.issPageValue);
            await paymentMethodPage.executePayment(paymentDetails!);
            await paymentMethodPage.nextPage();
        });
    } else {
        await test.step('PaymentMethodPage >> Skip to Order Confirmation', async () => {
            await paymentMethodPage.validateURL(paymentMethodPage.issPageValue);
            await paymentMethodPage.nextPage();
        });
    }

    await test.step('OrderConfirmationPage >> Validate order', async () => {
        await orderConfirmationPage.validateURL();
        await orderConfirmationPage.validateOrderConfirmationPage(testCase.testData);
    });
}
