import { setActivePinia, createPinia } from 'pinia';
import { useMainStore, getDefaultState } from '@/store/index.js';
import globalMethods from '@/global-methods.js';
import {
    getRandomString,
    getRandomGuid,
    getRandomInt,
    getRandomBoolean,
    getRandomEnum
} from '@/helpers/data-generation.js';
import coverageStatuses from '@/constants/coverage-statuses.js';
import { paymentMethods } from '@/constants/payment-method-constants';
import endpoints from '@/constants/endpoints';
import { AppointmentTypeStrings } from '@/constants/schedule-constants';
import coverageType from '@/constants/coverage-type';
import { getEnumName } from '@/helpers/unit-test-helper';
import { strictEqual } from 'assert';

describe('Store', () => {
    let store;

    beforeEach(() => {
        const pinia = createPinia();
        setActivePinia(pinia);

        store = useMainStore();
        const defaultState = getDefaultState();
        Object.keys(defaultState).forEach((key) => {
            store[key] = defaultState[key];
        });

        store.applicationUser.eventBus = [];
        jest.resetAllMocks();
    });

    it('Should Store Vehicle Year', () => {
        const testYear = '2001';
        store.updateVehicleYear(testYear);
        expect(store.order.vehicle.year).toEqual(testYear);
    });

    it('Should add events to the bus', () => {
        // Arrange
        const category = getRandomString(1, 25);
        const subCategory = getRandomString(5, 20);
        const isDismissible = getRandomBoolean();
        const copy = getRandomString(5, 25);
        const headline = getRandomString(5, 25);
        const type = getRandomString(5, 15);
        const event = {
            category,
            subCategory,
            eventValue: {
                isDismissible,
                messageCopy: copy,
                messageHeadline: headline,
                type
            }
        };

        // Act
        store.addEventToBus(event);

        // Assert
        expect(store.applicationUser.eventBus[0]).toEqual(event);
    });

    it('Should remove events from the bus', () => {
        // Arrange
        const category = getRandomString(1, 25);
        const subCategory = getRandomString(5, 20);
        const isDismissible = getRandomBoolean();
        const copy = getRandomString(5, 25);
        const headline = getRandomString(5, 25);
        const type = getRandomString(5, 15);
        const event = {
            category,
            subCategory,
            eventValue: {
                isDismissible,
                messageCopy: copy,
                messageHeadline: headline,
                type
            }
        };

        store.addEventToBus(event);

        expect(store.applicationUser.eventBus.length).toBe(1);

        // Act
        store.removeEventFromBus({ category: event.category, subCategory: event.subCategory });

        // Assert
        expect(store.applicationUser.eventBus.length).toBe(0);
    });

    it('Should return correct event using the getter function eventBusItem', () => {
        // Arrange
        const category = getRandomString(1, 25);
        const subCategory = getRandomString(5, 20);
        const isDismissible = getRandomBoolean();
        const copy = getRandomString(5, 25);
        const headline = getRandomString(5, 25);
        const type = getRandomString(5, 15);
        const event = {
            category,
            subCategory,
            eventValue: {
                isDismissible,
                messageCopy: copy,
                messageHeadline: headline,
                type
            }
        };

        store.addEventToBus(event);

        // Act
        const actual = store.eventBusItem(event.category, event.subCategory);

        // Assert
        expect(actual).toEqual(event.eventValue);
    });

    it('UpdateVehicle should merge vehicle with response object', () => {
        // Arrange
        const carId = getRandomString(10, 14);
        const category = getRandomString(3, 7);
        const year = getRandomInt(1960, 2023);
        const make = getRandomString(4, 10);
        const model = getRandomString(4, 10);
        const style = getRandomString(4, 15);
        const imageUrl = getRandomString(50, 100);
        const imageVifNumber = getRandomInt(10000, 99999).toString();
        const imageColor = getRandomString(4, 10);
        const providedVehicle = {
            carId,
            category,
            year,
            make,
            model,
            style,
            imageUrl,
            imageVifNumber,
            imageVifColor: imageColor
        };

        const expectedVehicle = {
            carId,
            category,
            year,
            make,
            model,
            style,
            imageUrl,
            imageVifNumber,
            imageColor
        };

        // Act
        store.updateVehicle(providedVehicle);

        // Assert
        expect(store.order.vehicle).toMatchObject(expectedVehicle);
    });

    it('updateVehicleCoverage should set policy values appropriately with repair waived', () => {
        // Arrange
        const noCoverage = getRandomBoolean();
        const deductible = getRandomInt(1, 500);
        const endorsements = [getRandomString(10, 20)];
        const vehicleCoverage = {
            noCoverage,
            deductible,
            repairWaived: true,
            endorsements
        };

        const expectedPolicy = {
            deductible: {
                replace: deductible,
                repair: 0
            },
            endorsements
        };

        // Act
        store.updateVehicleCoverage(vehicleCoverage);

        // Assert
        expect(store.order.policy).toMatchObject(expectedPolicy);
    });

    it('UpdateVehicle should set policy values appropriately with repair not waived', () => {
        // Arrange
        const noCoverage = getRandomBoolean();
        const deductible = getRandomInt(1, 500);
        const endorsements = [getRandomString(10, 20)];
        const vehicleCoverage = {
            noCoverage,
            deductible,
            repairWaived: false,
            endorsements
        };

        const expectedPolicy = {
            deductible: {
                replace: deductible,
                repair: deductible
            },
            endorsements
        };

        // Act
        store.updateVehicleCoverage(vehicleCoverage);

        // Assert
        expect(store.order.policy).toMatchObject(expectedPolicy);
    });

    describe.each([
        [coverageType.NO_COMP, true, true],
        [coverageType.NONE, false, true],
        [coverageType.Deductible, true, false]
    ])('updateVehicleCoverage noCoverage', (expected, enableNoCompQuote, noCoverage) => {
        test(`CoverageType is set to expected ${getEnumName(coverageType, expected)} when vehicle noCoverage is ${noCoverage} and enableNoCompQuote is ${enableNoCompQuote}`, () => {
            // Arrange
            store.issConfig.enableNoCompQuote = enableNoCompQuote;
            store.order.currentDeductible = {
                replace: 500,
                repair: 0
            };
            const vehicleCoverage = {
                noCoverage
            };

            // Act
            store.updateVehicleCoverage(vehicleCoverage);

            // Assert
            expect(store.order.insuranceCoverage.coverageType).toBe(expected);
        });
    });

    // TODO update test to work also checking store values
    it('setVehicle should call globalMethods.callHttpClient', () => {
        // Arrange
        const carId = getRandomString(10, 14);
        const category = getRandomString(3, 7);
        const year = getRandomInt(1960, 2023);
        const make = getRandomString(4, 10);
        const model = getRandomString(4, 10);
        const style = getRandomString(4, 15);
        const imageUrl = getRandomString(50, 100);
        const imageVifNumber = getRandomInt(10000, 99999).toString();
        const imageColor = getRandomString(4, 10);
        const response = {
            data: {
                carId,
                category,
                year,
                make,
                model,
                style,
                imageUrl,
                imageVifNumber,
                imageVifColor: imageColor
            }
        };

        globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

        // Act
        const returned = store.setVehicle();

        // Assert
        expect(globalMethods.callHttpClient).toHaveBeenCalled();
        expect(returned).resolves.toMatchObject(response);
    });

    it('saveVehicleDamage with windshield repair should update damage with number of chips not null', () => {
        // Arrange
        const glassName = getRandomString(4, 10);
        const glassLocation = getRandomString(5, 15);
        const isWindshieldRepair = true;
        const selectedGlassToReplace = [{
            glassName,
            glassLocation
        }];
        const chipCount = getRandomInt(0, 3);

        // Act
        store.saveVehicleDamage(isWindshieldRepair, selectedGlassToReplace, chipCount);

        // Assert
        expect(store.order.damage.glassToReplace).toEqual(selectedGlassToReplace);
        expect(store.order.damage.isRepair).toEqual(isWindshieldRepair);
        expect(store.order.damage.numberOfChips).toEqual(chipCount);
    });

    it('saveVehicleDamage without windshield repair should update damage with number of chips null', () => {
        // Arrange
        const glassName = getRandomString(4, 10);
        const glassLocation = getRandomString(5, 15);
        const isWindshieldRepair = false;
        const selectedGlassToReplace = [{
            glassName,
            glassLocation
        }];
        const chipCount = getRandomInt(0, 3);

        const expectedChipCount = null;

        // Act
        store.saveVehicleDamage(isWindshieldRepair, selectedGlassToReplace, chipCount);

        // Assert
        expect(store.order.damage.glassToReplace).toEqual(selectedGlassToReplace);
        expect(store.order.damage.isRepair).toEqual(isWindshieldRepair);
        expect(store.order.damage.numberOfChips).toEqual(expectedChipCount);
    });

    it('should return registration data if available', () => {
        // Arrange
        const streetAddress = getRandomString(5, 15);
        const city = getRandomString(5, 15);
        const state = getRandomString(5, 10);
        const zipCode = getRandomInt(10000, 99999).toString();
        const firstName = getRandomString(5, 20);
        const lastName = getRandomString(5, 20);
        const expected = {
            addressQuestions: {
                streetAddress,
                city,
                state,
                zipCode
            },
            firstName,
            lastName
        };

        store.order.vehicle.registration = {
            licensePlate: null,
            address: streetAddress,
            city,
            state,
            zipCode,
            firstName,
            lastName
        };

        // Act
        const actual = store.customerData;

        // Assert
        expect(actual).toEqual(expected);
    });

    it('should return customer data if registration data unavailable', () => {
        // Arrange
        const address = getRandomString(1, 25);
        const city = getRandomString(5, 20);
        const state = getRandomString(4, 20);
        const zipCode = getRandomInt(10000, 99999).toString();
        const firstName = getRandomString(5, 25);
        const lastName = getRandomString(5, 25);
        const expected = {
            addressQuestions: {
                streetAddress: address,
                city,
                state,
                zipCode
            },
            firstName,
            lastName
        };

        store.order.vehicle.registration.address = null;

        store.order.customer = {
            address: {
                streetAddress: address,
                city,
                state,
                zipCode
            },
            firstName,
            lastName
        };

        // Act
        const actual = store.customerData;

        // Assert
        expect(actual).toMatchObject(expected);
    });

    describe('registerClaim method', () => {
        it('successful response with no coverage => isVerified true and coverage status no comp', async () => {
            // Arrange
            const response = {
                data: {
                    claimantId: null,
                    claimNumber: getRandomString(9, 9),
                    referralCorrelationId: getRandomGuid(),
                    isSuccess: true,
                    isError: false,
                    successMessage: getRandomString(9, 9),
                    deductible: 0
                }
            };
            store.order.insuranceCoverage.coverageType = coverageType.NO_COMP;
            store.order.currentDeductible = {
                replace: 500,
                repair: 0
            };

            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

            // Act
            await store.registerClaim();

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
            expect(store.order.insuranceCoverage.coverageStatus).toBe(coverageStatuses.VERIFIED);
            expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.NO_COMP);
            expect(store.order.insuranceCoverage.claimNumber).toBe(response.data.claimNumber);
        });

        it('successful response with coverage => isVerified true and coverage status verified', async () => {
            // Arrange
            const response = {
                data: {
                    claimantId: null,
                    claimNumber: getRandomString(9, 9),
                    referralCorrelationId: getRandomGuid(),
                    isSuccess: true,
                    isError: false,
                    successMessage: getRandomString(9, 9),
                    deductible: 0
                }
            };
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.currentDeductible = {
                replace: 500,
                repair: 0
            };

            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

            // Act
            await store.registerClaim();

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
            expect(store.order.insuranceCoverage.coverageStatus).toBe(coverageStatuses.VERIFIED);
            expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.Deductible);
            expect(store.order.insuranceCoverage.claimNumber).not.toBeNull();
        });

        it('Call to client returns exception, resulting in object with error property being returned', async () => {
            // Arrange
            expect.assertions(4);
            const error = 'register claim error';
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));
            store.order.insuranceCoverage.coverageStatus = coverageStatuses.PENDING;
            store.order.currentDeductible = {
                replace: 500,
                repair: 0
            };

            // Act
            await store.registerClaim().catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
            expect(store.order.insuranceCoverage.coverageStatus).toBe(coverageStatuses.NO_COVERAGE);
            expect(store.order.insuranceCoverage.claimNumber).toBe(null);
        });
    });

    describe('updateContactInfo method', () => {
        it('UpdateContactInfo updates contact info in store', () => {
            // Arrange
            const firstName = getRandomString(4, 10);
            const lastName = getRandomString(5, 15);
            const emailAddress = false;
            const requestTextUpdates = getRandomBoolean();
            const notesForTechnician = getRandomString(50, 150);

            // Act
            store.updateContactInfo({ firstName,
                lastName,
                emailAddress,
                requestTextUpdates,
                notesForTechnician });

            // Assert
            expect(store.contactInfo.firstName).toEqual(firstName);
            expect(store.contactInfo.lastName).toEqual(lastName);
            expect(store.contactInfo.emailAddress).toEqual(emailAddress);
            expect(store.contactInfo.requestTextUpdates).toEqual(requestTextUpdates);
            expect(store.contactInfo.notesForTechnician).toEqual(notesForTechnician);
        });
        it('updatePhoneNumbers updates phone info in store', () => {
            // Arrange
            const homePhone = getRandomInt(1000000000, 9999999999);
            const servicePhone = getRandomInt(1000000000, 9999999999);
            const altPhone = getRandomInt(1000000000, 9999999999);
            const extension = getRandomInt(10000, 99999);

            // Act
            store.updatePhoneNumbers({
                home: homePhone,
                service: servicePhone,
                alternative: altPhone,
                extension
            });

            // Assert
            expect(store.contactInfo.homePhone).toEqual(homePhone);
            expect(store.contactInfo.servicePhone).toEqual(servicePhone);
            expect(store.contactInfo.alternativePhone).toEqual(altPhone);
            expect(store.contactInfo.extension).toEqual(extension);
        });
        it('All null values => contact info set in store to all nulls', () => {
            // Act
            store.updateContactInfo({});

            // Assert
            expect(store.contactInfo.firstName).toEqual('');
            expect(store.contactInfo.lastName).toEqual('');
            expect(store.contactInfo.emailAddress).toEqual('');
            expect(store.contactInfo.requestTextUpdates).toEqual(false);
            expect(store.contactInfo.notesForTechnician).toEqual('');
        });
    });

    describe('saveSession method', () => {
        describe('successful method call', () => {
            it('calls save session api endpoint', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.SaveSession.method,
                    endpoint: endpoints.SaveSession.url
                }));
            });
            it('Returns expected response object', async () => {
                // Arrange
                const response = { ReferralNumber: getRandomString(6, 6) };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

                // Act
                const result = store.saveSession({});

                // Asserts
                await expect(result).resolves.toBe(response);
            });
            it('calls api with expected application user data', async () => {
                // Arrange
                const crmCustomerId = getRandomString(6, 6);
                const experiments = getRandomString(6, 6);
                const lastPageVisited = getRandomString(6, 6);
                const pageData = getRandomString(6, 6);
                const savedSessionId = getRandomString(6, 6);
                store.applicationUser.crmCustomerId = crmCustomerId;
                store.applicationUser.experiments = experiments;
                store.applicationUser.lastPageVisited = lastPageVisited;
                store.applicationUser.pageData = pageData;
                store.applicationUser.savedSessionId = savedSessionId;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        applicationUser: expect.objectContaining({
                            crmCustomerId,
                            experiments,
                            lastPage: lastPageVisited,
                            pageData,
                            savedSessionId
                        })
                    })
                }));
            });
            it('calls api with expected vehicle', async () => {
                const year = getRandomString(6, 6);
                const make = getRandomString(6, 6);
                const model = getRandomString(6, 6);
                const style = getRandomString(6, 6);
                const carId = getRandomString(6, 6);
                const vin = getRandomString(6, 6);
                const licensePlate = getRandomString(6, 6);
                store.order.vehicle.year = year;
                store.order.vehicle.make = make;
                store.order.vehicle.model = model;
                store.order.vehicle.style = style;
                store.order.vehicle.carId = carId;
                store.order.vehicle.vin = vin;
                store.order.vehicle.registration.licensePlate = licensePlate;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        vehicle: expect.objectContaining({
                            year,
                            make,
                            model,
                            style,
                            carId,
                            vin,
                            licensePlateNumber: licensePlate
                        })
                    })
                }));
            });
            it('calls api with expected damage', async () => {
                // Arrange
                const isRepair = getRandomString(6, 6);
                const numberOfChips = getRandomString(6, 6);
                const partQuestionAnswers = getRandomString(6, 6);
                const moldingQuestionAnswers = getRandomString(6, 6);
                const capabilityQuestionAnswers = getRandomString(6, 6);
                const dateOfLoss = getRandomString(6, 6);
                const damageCause = getRandomString(6, 6);
                const damageState = getRandomString(6, 6);
                const damageCity = getRandomString(6, 6);
                const isDamageGlassOnly = getRandomString(6, 6);
                store.order.damage.isRepair = isRepair;
                store.order.damage.numberOfChips = numberOfChips;
                store.order.damage.partQuestionAnswers = partQuestionAnswers;
                store.order.damage.moldingQuestionAnswers = moldingQuestionAnswers;
                store.order.damage.capabilityQuestionAnswers = capabilityQuestionAnswers;
                store.order.policy.dateOfLoss = dateOfLoss;
                store.order.policy.damageCause = damageCause;
                store.order.policy.damageState = damageState;
                store.order.policy.damageCity = damageCity;
                store.order.policy.isDamageGlassOnly = isDamageGlassOnly;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        damage: expect.objectContaining({
                            numberOfChips,
                            isRepair,
                            partQuestionAnswers,
                            moldingQuestionAnswers,
                            capabilityQuestionAnswers,
                            dateOfLoss,
                            damageCause,
                            damageState,
                            damageCity,
                            isDamageGlassOnly
                        })
                    })
                }));
            });
            it('calls api with expected policy', async () => {
                // Arrange
                const customerFirstName = getRandomString(6, 6);
                const customerLastName = getRandomString(6, 6);
                const customerEmail = getRandomString(6, 6);
                const customerPhoneNumber = getRandomString(6, 6);
                const customerState = getRandomString(2, 2);
                const policyNumber = getRandomString(6, 6);
                const policyZipCode = getRandomString(6, 6);
                const status = getRandomEnum(coverageStatuses);
                const type = getRandomEnum(coverageType);
                const originalDeductible = {
                    replace: 500,
                    repair: 0
                };
                const currentDeductible = {
                    replace: 500,
                    repair: 0
                };
                store.order.originalDeductible = {
                    replace: originalDeductible.replace,
                    repair: originalDeductible.repair
                };
                store.order.currentDeductible = {
                    replace: currentDeductible.replace,
                    repair: currentDeductible.repair
                };
                store.order.customer.firstName = customerFirstName;
                store.order.customer.lastName = customerLastName;
                store.order.customer.emailAddress = customerEmail;
                store.order.customer.address.state = customerState;
                store.order.contactInfo.homePhone = customerPhoneNumber;
                store.order.contactInfo.servicePhone = customerPhoneNumber;
                store.order.policy.policyNumber = policyNumber;
                store.order.policy.policyZipCode = policyZipCode;
                store.order.insuranceCoverage.coverageStatus = status;
                store.order.insuranceCoverage.coverageType = type;
                store.order.damage.isRepair = false;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        policy: expect.objectContaining({
                            policyHolder: expect.objectContaining({
                                policyFirstName: customerFirstName,
                                policyLastName: customerLastName,
                                policyPhoneNumber: customerPhoneNumber,
                                policyEmail: customerEmail,
                                policyState: customerState
                            }),
                            policyNumber,
                            policyZipCode,
                            originalDeductible: originalDeductible.replace,
                            currentDeductible: currentDeductible.replace
                        }),
                        insuranceCoverage: expect.objectContaining({
                            coverageStatus: status,
                            coverageType: type
                        })
                    })
                }));
            });
            it('calls api with expected customer', async () => {
                // Arrange
                const streetAddress = getRandomString(6, 6);
                const streetAddress2 = getRandomString(6, 6);
                const city = getRandomString(6, 6);
                const state = getRandomString(6, 6);
                const zipCode = getRandomString(6, 6);
                const contactFirstName = getRandomString(6, 6);
                const contactLastName = getRandomString(6, 6);
                const contactEmail = getRandomString(6, 6);
                const contactHomePhone = getRandomString(6, 6);
                const contactServicePhone = getRandomString(6, 6);
                const contactAlternativePhone = getRandomString(6, 6);
                const requestTextUpdates = getRandomBoolean();
                store.order.contactInfo.firstName = contactFirstName;
                store.order.contactInfo.lastName = contactLastName;
                store.order.contactInfo.emailAddress = contactEmail;
                store.order.contactInfo.homePhone = contactHomePhone;
                store.order.contactInfo.servicePhone = contactServicePhone;
                store.order.contactInfo.alternativePhone = contactAlternativePhone;
                store.order.contactInfo.requestTextUpdates = requestTextUpdates;
                store.order.customer.address.streetAddress = streetAddress;
                store.order.customer.address.streetAddress2 = streetAddress2;
                store.order.customer.address.city = city;
                store.order.customer.address.state = state;
                store.order.customer.address.zipCode = zipCode;

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        customer: expect.objectContaining({
                            address: expect.objectContaining({
                                streetAddress,
                                streetAddress2,
                                city,
                                state,
                                zipCode
                            }),
                            emailAddress: contactEmail,
                            firstName: contactFirstName,
                            lastName: contactLastName,
                            homePhone: contactHomePhone,
                            servicePhone: contactServicePhone,
                            alternativePhone: contactAlternativePhone,
                            isSmsOptIn: requestTextUpdates
                        })
                    })
                }));
            });
            it('calls api with expected lineItems', async () => {
                // Arrange
                const glassParts = [{
                    partNumber: getRandomString(6, 6),
                    clearOnSubmit: false
                }];
                const supportingItems = [{
                    partNumber: getRandomString(6, 6),
                    clearOnSubmit: false
                }];
                const vaps = [{
                    partNumber: getRandomString(6, 6),
                    clearOnSubmit: false
                }];
                store.order.lineItems.glassParts = glassParts;
                store.order.lineItems.supportingItems = supportingItems;
                store.order.lineItems.vaps = vaps;

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        lineItems: expect.objectContaining({
                            glassParts,
                            supportingItems,
                            vaps
                        })
                    })
                }));
            });
            describe.each([
                [coverageStatuses.PENDING, coverageType.NO_COMP, null],
                [coverageStatuses.PENDING, coverageType.ITAC, null],
                [coverageStatuses.PENDING, coverageType.Deductible, null],
                [coverageStatuses.VERIFIED, coverageType.ITAC, 'V_ITAC_123'],
                [coverageStatuses.VERIFIED, coverageType.Deductible, 'V_Deductible_123'],
                [coverageStatuses.NO_COVERAGE, coverageType.NONE, null]
            ])('calls api with expected insuranceCoverage', (status, type, claimNumber) => {
                test(`calls api with coverageStatus is ${getEnumName(coverageStatuses, status)} and coverageType is ${getEnumName(coverageType, type)} and claimNumber is ${claimNumber}`, async () => {
                    // Arrange
                    store.order.insuranceCoverage.coverageStatus = status;
                    store.order.insuranceCoverage.coverageType = type;
                    store.order.insuranceCoverage.claimNumber = claimNumber;
                    globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                    // Act
                    await store.saveSession({});

                    // Assert
                    expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                        payload: expect.objectContaining({
                            insuranceCoverage: expect.objectContaining({
                                coverageStatus: status,
                                coverageType: type,
                                claimNumber
                            })
                        })
                    }));
                });
            });
            it('calls api with expected payment', async () => {
                // Arrange
                const parentAccountNumber = getRandomString(6, 6);
                store.order.parentAccountNumber = parentAccountNumber;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        payment: expect.objectContaining({
                            parentAccountNumber
                        })
                    })
                }));
            });
            it('calls api with expected service location', async () => {
                // Arrange
                const notesForTechnician = getRandomString(6, 6);
                const address = getRandomString(6, 6);
                const city = getRandomString(6, 6);
                const state = getRandomString(6, 6);
                const zipCode = getRandomString(6, 6);
                const zipCodeCtu = getRandomString(6, 6);

                store.order.contactInfo.notesForTechnician = notesForTechnician;
                store.order.serviceLocation.address = address;
                store.order.serviceLocation.city = city;
                store.order.serviceLocation.state = state;
                store.order.serviceLocation.zipCode = zipCode;
                store.order.serviceLocation.zipCodeCtu = zipCodeCtu;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        serviceLocation: expect.objectContaining({
                            address: expect.objectContaining({
                                streetAddress: address,
                                city,
                                state,
                                zipCode,
                                zipCodeCtu
                            }),
                            techNotes: notesForTechnician
                        })
                    })
                }));
            });
            it('calls api with expected schedule', async () => {
                // Arrange
                const date = getRandomString(6, 6);
                const startTime = getRandomString(6, 6);
                const endTime = getRandomString(6, 6);
                const routeCode = getRandomString(6, 6);
                const jobMaxMinutes = getRandomString(6, 6);
                const jobMinMinutes = getRandomString(6, 6);
                store.order.schedule.date = date;
                store.order.schedule.startTime = startTime;
                store.order.schedule.endTime = endTime;
                store.order.schedule.routeCode = routeCode;
                store.order.schedule.jobMaxMinutes = jobMaxMinutes;
                store.order.schedule.jobMinMinutes = jobMinMinutes;

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        schedule: expect.objectContaining({
                            date,
                            startTime,
                            endTime,
                            routeCode,
                            jobMaxMinutes,
                            jobMinMinutes
                        })
                    })
                }));
            });
            it('calls api with expected referral date', async () => {
                // Arrange
                const referralDate = getRandomString(6, 6);
                store.order.referralDate = referralDate;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({ referralDate })
                }));
            });
            it('calls api with expected referral number', async () => {
                // Arrange
                const referralNumber = getRandomString(6, 6);
                store.order.referralNumber = referralNumber;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.saveSession({});

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({ referralNumber })
                }));
            });
        });
        it('No glassArray => empty list', async () => {
            store.damage.glassToReplace = null;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

            // Act
            await store.saveSession({});

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                payload: expect.objectContaining({
                    damage: expect.objectContaining({
                        glassToReplace: []
                    })
                })
            }));
        });
        it('glassArray empty => empty list', async () => {
            store.damage.glassToReplace = [];
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

            // Act
            await store.saveSession({});

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                payload: expect.objectContaining({
                    damage: expect.objectContaining({
                        glassToReplace: []
                    })
                })
            }));
        });
        it('Nonempty glass array => expected glass array sent', async () => {
            const location1 = getRandomString(5);
            const location2 = getRandomString(5);
            const name1 = getRandomString(10);
            const name2 = getRandomString(10);
            store.damage.glassToReplace = [
                { glassLocation: location1, glassName: name1 },
                { glassLocation: location2, glassName: name2 }
            ];
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

            // Act
            await store.saveSession({});

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                payload: expect.objectContaining({
                    damage: expect.objectContaining({
                        glassToReplace: expect.arrayContaining([
                            { location: location1, name: name1 },
                            { location: location2, name: name2 }
                        ])
                    })
                })
            }));
        });
        it('calls api with expected submitAfterSave', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

            // Act
            await store.saveSession({ submitAfterSave: true });

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                payload: expect.objectContaining({
                    submitAfterSave: true
                })
            }));
        });
        it('api call throws exception', async () => {
            expect.assertions(2);
            const error = 'save session error';
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            // Act
            await store.saveSession({}).catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                method: endpoints.SaveSession.method,
                endpoint: endpoints.SaveSession.url
            }));
        });
    });

    describe('loadSession method', () => {
        describe('successful method call', () => {
            const applicationUser = {
                experiments: getRandomString(6, 6)
            };
            const vehicle = {
                    year: getRandomInt(2000, 2024).toString(),
                    make: getRandomString(5, 15),
                    model: getRandomString(5, 15),
                    style: getRandomString(5, 15),
                    carId: getRandomInt(1000, 9999),
                    vin: getRandomString(17, 17),
                    licensePlateNumber: getRandomString(7, 7)
            };
            const customer= {
                address: {
                    streetAddress: getRandomString(10, 50),
                    streetAddress2: getRandomString(5, 20),
                    city: getRandomString(5, 20),
                    state: getRandomString(2, 2),
                    zipCode: getRandomString(5, 5)
                },
                firstName: getRandomString(5, 15),
                lastName: getRandomString(5, 15),
                emailAddress: `${getRandomString(5, 10)}@test.com`,
                homePhone: getRandomString(10, 10),
                servicePhone: getRandomString(10, 10),
                alternativePhone: getRandomString(10, 10),
                isSmsOptIn: getRandomBoolean()
            };
            const fullApiResponse = {
                data: {
                    applicationUser,
                    vehicle,
                    customer,
                    referralNumber: getRandomString(6, 6),
                    referralDate: getRandomString(6, 6),
                    referralCorrelationId: getRandomString(6, 6),
                    referralSequenceNumber: getRandomString(6, 6),
                    eon: getRandomString(6, 6)
                }
            };

            it('calls load session api endpoint', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({ data: {} }));
                const duplicate = {
                    referralNumber: getRandomString(6, 6),
                    referralCorrelationId: getRandomGuid()
                };

                // Act
                store.loadSession(duplicate);

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.LoadSession.method,
                    endpoint: endpoints.LoadSession.url
                }));
            });
            it('sets expected vehicle data', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(fullApiResponse));
                store.lookupVehicleByVin = jest.fn().mockReturnValue(Promise.resolve({
                    data: {
                        vin: vehicle.vin,
                        canSafeliteService: true
                    }
                }));

                const duplicate = {
                    referralNumber: getRandomString(6, 6),
                    referralCorrelationId: getRandomGuid()
                };

                store.order.insuranceCoverage.coverageType = coverageType.Deductible;
                store.policy.vehicles = [{ vehicle }];

                // Act
                await store.loadSession(duplicate);

                // Asserts
                expect(store.vehicle.year).toBe(vehicle.year);
                expect(store.vehicle.make).toBe(vehicle.make);
                expect(store.vehicle.model).toBe(vehicle.model);
                expect(store.vehicle.style).toBe(vehicle.style);
                // vin is not set directly by loadSession, it's set by updateVehicle after lookupVehicleByVin
                expect(store.vehicle.registration.licensePlate).toBe(vehicle.licensePlateNumber);
            });
            it('sets expected customer data', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(fullApiResponse));
                store.lookupVehicleByVin = jest.fn().mockReturnValue(Promise.resolve({
                    data: {
                        vin: vehicle.vin,
                        canSafeliteService: true
                    }
                }));

                const duplicate = {
                    referralNumber: getRandomString(6, 6),
                    referralCorrelationId: getRandomGuid()
                };

                store.order.insuranceCoverage.coverageType = coverageType.Deductible;
                store.policy.vehicles = [{ vin: vehicle.vin }];

                // Act
                await store.loadSession(duplicate);

                // Asserts
                expect(store.order.customer.address.streetAddress).toBe(customer.address.streetAddress);
                expect(store.order.customer.address.streetAddress2).toBe(customer.address.streetAddress2);
                expect(store.order.customer.address.city).toBe(customer.address.city);
                expect(store.order.customer.address.state).toBe(customer.address.state);
                expect(store.order.customer.address.zipCode).toBe(customer.address.zipCode);
                expect(store.order.contactInfo.homePhone).toBe(customer.homePhone);
            });
            it('sets expected remaining order data', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(fullApiResponse));
                store.lookupVehicleByVin = jest.fn().mockReturnValue(Promise.resolve({
                    data: {
                        vin: vehicle.vin,
                        canSafeliteService: true
                    }
                }));

                const duplicate = {
                    referralNumber: getRandomString(6, 6),
                    referralCorrelationId: getRandomGuid()
                };

                // Act
                await store.loadSession(duplicate);

                // Asserts
                expect(store.order.referralNumber).toBe(fullApiResponse.data.referralNumber);
                expect(store.order.referralDate).toBe(fullApiResponse.data.referralDate);
                expect(store.order.referralCorrelationId).toBe(fullApiResponse.data.referralCorrelationId);
                expect(store.order.referralSequenceNumber).toBe(fullApiResponse.data.referralSequenceNumber);
                expect(store.order.eon).toBe(fullApiResponse.data.eon);
            });
        });
        it('api call throws exception', async () => {
            expect.assertions(2);
            const error = 'load session error';
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            const duplicate = {
                referralNumber: getRandomString(6, 6),
                referralCorrelationId: getRandomGuid()
            };

            // Act
            await store.loadSession(duplicate).catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient)
                .toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.LoadSession.method,
                    endpoint: endpoints.LoadSession.url
                }));
        });
    });

    describe('getCoveragePolicyInfo method', () => {
        describe('successful method call', () => {
            it('calls getCoveragePolicyInfo api endpoint', async () => {
                // Arrange
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.CoveragePolicyInfo.method,
                    endpoint: endpoints.CoveragePolicyInfo.url
                }));
            });
            it('Sets policy fields for successful policy lookup', async () => {
                // Arrange
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;

                const address = getRandomString(6, 6);
                const city = getRandomString(6, 6);
                const state = getRandomString(6, 6);
                const zipCode = getRandomString(6, 6);
                const firstName = getRandomString(6, 6);
                const lastName = getRandomString(6, 6);

                const vehicle = { id: '123' };

                const response = {
                    data: {
                        policies: [
                            {
                                insureds: [
                                    {
                                        address,
                                        city,
                                        state,
                                        zipCode,
                                        firstName,
                                        lastName
                                    }
                                ],
                                vehicles: [
                                    vehicle
                                ]
                            }
                        ]
                    }
                };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                await expect(store.order.customer.address.streetAddress).toBe(address);
                await expect(store.order.customer.address.city).toBe(city);
                await expect(store.order.customer.address.state).toBe(state);
                await expect(store.order.customer.address.zipCode).toBe(zipCode);
                await expect(store.order.customer.firstName).toBe(firstName);
                await expect(store.order.customer.lastName).toBe(lastName);
                await expect(store.order.policy.vehicles).toStrictEqual([vehicle]);
            });
            it('calls api with expected data', async () => {
                // Arrange
                const parentAccountNumber = getRandomString(6, 6);
                const policyNumber = getRandomString(6, 6);
                const dateOfLoss = getRandomString(6, 6);
                const zipCode = getRandomString(6, 6);
                const referralCorrelationId = getRandomString(6, 6);
                store.order.parentAccountNumber = parentAccountNumber;
                store.order.policy.policyNumber = policyNumber;
                store.order.policy.dateOfLoss = dateOfLoss;
                store.order.policy.policyZipCode = zipCode;
                store.order.referralCorrelationId = referralCorrelationId;
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    payload: expect.objectContaining({
                        accountNumber: parentAccountNumber,
                        policyNumber,
                        dateOfLoss,
                        zipCode,
                        referralCorrelationId
                    })
                }));
            });
            it('null response by api => insuranceCoverage.coverageType is NONE', async () => {
                // Arrange
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(null));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.NONE);
            });
            it('no policies returned by api => insuranceCoverage.coverageType is NONE', async () => {
                // Arrange
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                const responseNoPolicies = {
                    data: {
                        policies: []
                    }
                };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseNoPolicies));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.NONE);
            });
            it('multiple policies returned by api => data set based on first policy returned', async () => {
                // Arrange
                const insured = {
                    address: getRandomString(6, 6),
                    firstName: getRandomString(6, 6),
                    lastName: getRandomString(6, 6),
                    city: getRandomString(6, 6),
                    state: getRandomString(6, 6),
                    zipCode: getRandomString(6, 6)
                };
                const vehicles = [
                    { name: getRandomString(6, 6) },
                    { name: getRandomString(6, 6) }
                ];
                const policy1 = {
                    insureds: [insured],
                    vehicles
                };
                const responseNoPolicies = {
                    data: {
                        policies: [policy1, {}]
                    }
                };
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseNoPolicies));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.Deductible);

                expect(store.order.customer.address.streetAddress).toBe(insured.address);
                expect(store.order.customer.address.city).toBe(insured.city);
                expect(store.order.customer.address.state).toBe(insured.state);
                expect(store.order.customer.address.zipCode).toBe(insured.zipCode);
                expect(store.order.customer.firstName).toBe(insured.firstName);
                expect(store.order.customer.lastName).toBe(insured.lastName);

                expect(store.order.policy.vehicles).toEqual(vehicles);
            });
            it('multiple insureds on first policy returned by api => data set based on first insured in first policy', async () => {
                // Arrange
                const insured1 = {
                    address: getRandomString(6, 6),
                    firstName: getRandomString(6, 6),
                    lastName: getRandomString(6, 6),
                    city: getRandomString(6, 6),
                    state: getRandomString(6, 6),
                    zipCode: getRandomString(6, 6)
                };
                const responseNoPolicies = {
                    data: {
                        policies: [{
                            insureds: [insured1, { address: getRandomString(6, 6) }]
                        }]
                    }
                };
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseNoPolicies));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.Deductible);
                expect(store.order.customer.address.streetAddress).toBe(insured1.address);
            });
            it('no policy vehicles on first policy => order.policy.vehicles empty list', async () => {
                // Arrange
                const responseNoPolicies = {
                    data: {
                        policies: [{ vehicles: [] }]
                    }
                };
                store.issConfig.isCoverageEnabled = true;
                store.applicationUser.coverageLookupAttempts = 0;
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseNoPolicies));

                // Act
                await store.getCoveragePolicyInfo();

                // Asserts
                expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.Deductible);
                expect(store.order.policy.vehicles).toEqual([]);
            });
        });

        test('if isCoverageEnabled is false, then getCoveragePolicyInfo not called', async () => {
            // Arrange
            store.issConfig.isCoverageEnabled = false;
            store.applicationUser.coverageLookupAttempts = 0;

            // Act
            await store.getCoveragePolicyInfo();

            // Assert
            expect(globalMethods.callHttpClient).not.toHaveBeenCalled();
        });
        test('if isCoverageEnabled is true, then getCoveragePolicyInfo called', async () => {
            // Arrange
            store.issConfig.isCoverageEnabled = true;
            store.applicationUser.coverageLookupAttempts = 0;

            // Act
            await store.getCoveragePolicyInfo();

            // Assert
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
        });
        test('if maxCoverageLookupAttemptsReached is true, then getCoveragePolicyInfo not called', async () => {
            // Arrange
            store.issConfig.isCoverageEnabled = true;
            store.applicationUser.coverageLookupAttempts = 11;

            // Act
            await store.getCoveragePolicyInfo();

            // Assert
            expect(globalMethods.callHttpClient).not.toHaveBeenCalled();
        });
        test('if maxCoverageLookupAttemptsReached is false, then getCoveragePolicyInfo called', async () => {
            // Arrange
            store.issConfig.isCoverageEnabled = true;
            store.applicationUser.coverageLookupAttempts = 10;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve());

            // Act
            await store.getCoveragePolicyInfo();

            // Assert
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
        });
        it('api call throws exception => insuranceCoverage.coverageType is NONE', async () => {
            expect.assertions(3);
            const error = 'get coverage policy info error';
            store.issConfig.isCoverageEnabled = true;
            store.applicationUser.coverageLookupAttempts = 0;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            // Act
            await store.getCoveragePolicyInfo().catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient)
                .toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.CoveragePolicyInfo.method,
                    endpoint: endpoints.CoveragePolicyInfo.url
                }));
            expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.NONE);
        });
    });

    describe('saveEndorsementQuestionAnswers method', () => {
        it('method should update endorsement question data in store', () => {
            // Arrange
            const questionNum = getRandomInt(1, 100);
            const questionText = getRandomString(50, 300);
            const selectedAnswer = getRandomString(2, 3);
            const endorsementQuestionAnswersArray = [
                {
                    questionNum,
                    questionText,
                    selectedAnswer
                }
            ];

            // Act
            store.saveEndorsementQuestionAnswers(endorsementQuestionAnswersArray);

            // Assert
            expect(store.order.policy.endorsementQuestionAnswers).toEqual(endorsementQuestionAnswersArray);
        });
    });

    describe('duplicateSearch method', () => {
        it('successful response => duplicateReferrals set to expected', async () => {
            // Arrange
            const expected = [
                {
                    accountNumber: getRandomString(6, 6),
                    claimNumber: getRandomString(9, 9)
                },
                {
                    accountNumber: getRandomString(6, 6),
                    claimNumber: getRandomString(9, 9)
                },
                {
                    accountNumber: getRandomString(6, 6),
                    claimNumber: getRandomString(9, 9)
                }];
            const response = {
                data: expected
            };

            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

            // Act
            await store.getDuplicateReferrals();

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
            expect(store.applicationUser.duplicateOrders).toEqual(expected);
        });
        it('Call to client returns exception => object with error property returned and duplicateReferrals set to []', async () => {
            // Arrange
            expect.assertions(3);
            const error = 'get duplicate referrals error';
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            // Act
            await store.getDuplicateReferrals().catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient).toHaveBeenCalled();
            expect(store.applicationUser.duplicateOrders.length).toBe(0);
        });
    });

    describe.each([
        [true, coverageStatuses.PENDING],
        [true, coverageStatuses.NO_COVERAGE],
        [false, coverageStatuses.VERIFIED]
    ])('isUnverified', (expected, status) => {
        test(`returns ${expected} when coverageStatus is ${getEnumName(coverageStatuses, status)}`, () => {
            // Arrange
            store.order.insuranceCoverage.coverageStatus = status;

            // Act
            const result = store.isUnverified;

            // Assert
            expect(result).toBe(expected);
        });
    });

    describe('isMobileAppointment', () => {
        it('Should return true for mobile appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({
                appointmentType: AppointmentTypeStrings.MOBILE
            });

            // Assert
            expect(store.isMobileAppointment).toBe(true);
        });

        it('Should return true for mobile-NotITAC-and-NotNoComp appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({
                appointmentType: AppointmentTypeStrings.MOBILE_NOT_ITAC_AND_NOT_NOCOMP
            });

            // Assert
            expect(store.isMobileAppointment).toBe(true);
        });

        it('Should return false for non-mobile appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({
                appointmentType: AppointmentTypeStrings.IN_SHOP
            });

            // Assert
            expect(store.isMobileAppointment).toBe(false);
        });

        it('Should return false for null appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({ appointmentType: null });

            // Assert
            expect(store.isMobileAppointment).toBe(false);
        });
    });

    describe('isDropoffAppointment', () => {
        it('Should return true for drop-off appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({
                appointmentType: AppointmentTypeStrings.DROP_OFF
            });

            // Assert
            expect(store.isDropOffAppointment).toBe(true);
        });

        it('Should return false for non-drop-off appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({
                appointmentType: AppointmentTypeStrings.MOBILE
            });

            // Assert
            expect(store.isDropOffAppointment).toBe(false);
        });

        it('Should return false for null appointments', () => {
            // Arrange

            // Act
            store.updateServiceLocation({ appointmentType: null });

            // Assert
            expect(store.isDropOffAppointment).toBe(false);
        });
    });

    describe('getFinalDeductible method', () => {
        describe('successful method call', () => {
            it('calls get final deductible api endpoint', () => {
                // Arrange
                const response = {
                    data: {
                        deductible: getRandomInt(0, 5000),
                        policyData: getRandomString(100, 200)
                    }
                };

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));
                store.order.damage.glassToReplace = [getRandomString(10, 15)];

                // Act
                store.getFinalDeductible();

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.FinalDeductible.method,
                    endpoint: endpoints.FinalDeductible.url
                }));
            });
            it('returns expected response object', async () => {
                // Arrange
                const response = {
                    data: {
                        deductible: getRandomInt(0, 5000),
                        policyData: getRandomString(100, 200)
                    }
                };

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));
                store.order.damage.glassToReplace = [getRandomString(10, 15)];

                // Act
                const result = store.getFinalDeductible();

                // Assert
                await expect(result).resolves.toBe(response);
            });
            it('calls api with expected payload', () => {
                // Arrange
                const response = {
                    data: {
                        deductible: getRandomInt(0, 5000),
                        policyData: getRandomString(100, 200)
                    }
                };

                const location = getRandomString(10, 15).toUpperCase();
                store.order.damage.glassToReplace = [
                    {
                        glassLocation: location
                    }
                ];
                const referralCorrelationId = getRandomGuid();
                const parentAccountNumber = getRandomString(6, 6);
                const endorsements = [];
                const manualGlassNames = [location];
                const policyState = getRandomString(2, 2);
                const status = getRandomString(6, 8);
                const currentDeductible = 500;
                const originalDeductible = 500;
                const isRepair = getRandomBoolean();
                const policyNumber = getRandomString(10, 20);
                const insuredFirstName = getRandomString(10, 20);
                const insuredLastName = getRandomString(10, 20);
                const insuredZipCode = getRandomInt(10000, 99999).toString();
                const policyVehicleId = getRandomInt(1, 2).toString();
                const vehicleVin = getRandomString(17, 17);
                const policyData = getRandomString(100, 200);

                store.order.referralCorrelationId = referralCorrelationId;
                store.order.parentAccountNumber = parentAccountNumber;
                store.order.currentDeductible = {
                    replace: currentDeductible,
                    repair: currentDeductible
                };
                store.order.originalDeductible = {
                    replace: originalDeductible,
                    repair: originalDeductible
                };
                store.order.policy.status = status;
                store.order.customer.address.state = policyState;
                store.order.damage.isRepair = isRepair;
                store.order.policy.policyNumber = policyNumber;
                store.order.customer.firstName = insuredFirstName;
                store.order.customer.lastName = insuredLastName;
                store.order.customer.address.zipCode = insuredZipCode;
                store.order.vehicle.policyVehicleId = policyVehicleId;
                store.order.vehicle.vin = vehicleVin;
                store.order.policy.policyData = policyData;

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

                // Act
                store.getFinalDeductible();

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(({
                    method: endpoints.FinalDeductible.method,
                    endpoint: endpoints.FinalDeductible.url,
                    payload: ({
                        referralCorrelationId,
                        accountNumber: parentAccountNumber,
                        endorsements,
                        manualGlassNames,
                        policyState,
                        status,
                        currentDeductible,
                        originalDeductible,
                        noCoverage: store.isNoComp,
                        isRepair,
                        policyNumber,
                        insuredFirstName,
                        insuredLastName,
                        insuredZipCode,
                        policyVehicleId,
                        vehicleVin,
                        policyData,
                        isItac: store.isITAC
                    })
                }));
            });
            it('only "Yes" endorsement answers are added to payload', () => {
                // Arrange
                const response = {
                    data: {
                        deductible: getRandomInt(0, 5000),
                        policyData: getRandomString(100, 200)
                    }
                };

                const location = getRandomString(10, 15).toUpperCase();
                store.order.damage.glassToReplace = [
                    {
                        glassLocation: location
                    }
                ];
                const referralCorrelationId = getRandomGuid();
                const parentAccountNumber = getRandomString(6, 6);
                const manualGlassNames = [location];
                const policyState = getRandomString(2, 2);
                const status = getRandomString(6, 8);
                const currentDeductible = getRandomInt(0, 5000);
                const originalDeductible = getRandomInt(0, 5000);
                const isRepair = getRandomBoolean();
                const endorsementAnswers = [
                    {
                        questionNum: getRandomInt(1, 10),
                        endorsementName: getRandomString(8, 20),
                        questionText: getRandomString(50, 100),
                        selectedAnswer: 'Yes'
                    },
                    {
                        questionNum: getRandomInt(1, 10),
                        endorsementName: getRandomString(8, 20),
                        questionText: getRandomString(50, 100),
                        selectedAnswer: 'Yes'
                    },
                    {
                        questionNum: getRandomInt(1, 10),
                        endorsementName: getRandomString(8, 20),
                        questionText: getRandomString(50, 100),
                        selectedAnswer: 'No'
                    }
                ];
                const policyNumber = getRandomString(10, 20);
                const insuredFirstName = getRandomString(10, 20);
                const insuredLastName = getRandomString(10, 20);
                const insuredZipCode = getRandomInt(10000, 99999).toString();
                const policyVehicleId = getRandomInt(1, 2).toString();
                const vehicleVin = getRandomString(17, 17);
                const policyData = getRandomString(100, 200);

                store.order.referralCorrelationId = referralCorrelationId;
                store.order.parentAccountNumber = parentAccountNumber;
                store.order.currentDeductible = {
                    replace: currentDeductible,
                    repair: currentDeductible
                };
                store.order.originalDeductible = {
                    replace: originalDeductible,
                    repair: originalDeductible
                };
                store.order.policy.status = status;
                store.order.customer.address.state = policyState;
                store.order.policy.endorsementQuestionAnswers = endorsementAnswers;
                store.order.damage.isRepair = isRepair;
                store.order.policy.policyNumber = policyNumber;
                store.order.customer.firstName = insuredFirstName;
                store.order.customer.lastName = insuredLastName;
                store.order.customer.address.zipCode = insuredZipCode;
                store.order.vehicle.policyVehicleId = policyVehicleId;
                store.order.vehicle.vin = vehicleVin;
                store.order.policy.policyData = policyData;

                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));

                // Act
                store.getFinalDeductible();

                // Assert
                const expected = [endorsementAnswers[0].endorsementName, endorsementAnswers[1].endorsementName];
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(({
                    method: endpoints.FinalDeductible.method,
                    endpoint: endpoints.FinalDeductible.url,
                    payload: ({
                        referralCorrelationId,
                        accountNumber: parentAccountNumber,
                        endorsements: expected,
                        manualGlassNames,
                        policyState,
                        status,
                        currentDeductible,
                        originalDeductible,
                        noCoverage: store.isNoComp,
                        isRepair,
                        policyNumber,
                        insuredFirstName,
                        insuredLastName,
                        insuredZipCode,
                        policyVehicleId,
                        vehicleVin,
                        policyData,
                        isItac: store.isITAC
                    })
                }));
            });
        });
        describe('unsuccessful api call', () => {
            it('api call throws exception', async () => {
                // Arrange
                expect.assertions(2);
                const error = 'final deductible error';
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

                // Act
                await store.getFinalDeductible().catch((e) => {
                    expect(e).toEqual(error);
                });

                // Assert
                expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.FinalDeductible.method,
                    endpoint: endpoints.FinalDeductible.url
                }));
            });
        });
    });

    describe('updateDeductible method', () => {
        it('final deductible is saved as currentDeductible in store', () => {
            // Arrange
            store.order.damage.isRepair = false;
            const deductibleInfo = {
                deductible: 500
            };

            // Act
            store.updateDeductible(deductibleInfo);

            // Assert
            expect(store.order.currentDeductible.replace).toEqual(deductibleInfo.deductible);
        });
        it('null final deductible => currentDeductible in store set to null', () => {
            // Arrange
            store.order.damage.isRepair = false;
            const deductibleInfo = {
                deductible: null
            };

            // Act
            store.updateDeductible(deductibleInfo);

            // Assert
            expect(store.order.currentDeductible.replace).toEqual(deductibleInfo.deductible);
        });
    });

    describe('getTpaProviders method', () => {
        describe('successful method call', () => {
            it.each([[true, 'Repair'], [false, 'Replace']])(
                'calls getProviders api endpoint',
                async (isRepair, damageType) => {
                    // Arrange
                    globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({}));

                    const carId = getRandomString(10, 14);
                    const parentAccountNumber = getRandomString(6, 6);
                    store.order.parentAccountNumber = parentAccountNumber;
                    store.order.damage.isRepair = isRepair;
                    store.order.vehicle.carId = carId;
                    const zipCode = getRandomString(6, 6);
                    const radius = getRandomInt(5, 100);
                    const isBigTruck = false;
                    store.order.vehicle.isBigTruck = isBigTruck;
                    const expectedEndpoint = [
                        endpoints.GetProviders.url,
                        zipCode,
                        damageType,
                        radius,
                        parentAccountNumber,
                        'false',
                        carId,
                        isBigTruck
                    ].join('/');

                    // Act
                    await store.getTpaProviders(zipCode, radius);

                    // Asserts
                    expect(globalMethods.callHttpClient).toHaveBeenCalledWith(expect.objectContaining({
                        method: endpoints.GetProviders.method,
                        endpoint: expectedEndpoint
                    }));
                }
            );
            it('Returns expected response object', async () => {
                // Arrange
                const response = { ReferralNumber: getRandomString(6, 6) };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(response));
                const zipCode = getRandomString(6, 6);
                const radius = getRandomInt(5, 100);

                // Act
                const result = store.getTpaProviders(zipCode, radius);

                // Asserts
                await expect(result).resolves.toBe(response);
            });
            it('null response by api => no exceptions thrown', async () => {
                // Arrange
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(null));
                const zipCode = getRandomString(6, 6);
                const radius = getRandomInt(5, 100);

                // Act
                await store.getTpaProviders(zipCode, radius);
            });
            it('no providers returned by api => promise resolves to empty list', async () => {
                // Arrange
                const responseNoProviders = {
                    data: {
                        shopProviders: []
                    }
                };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseNoProviders));
                const zipCode = getRandomString(6, 6);
                const radius = getRandomInt(5, 100);

                // Act
                const result = await store.getTpaProviders(zipCode, radius);

                // Asserts
                expect(result.data.shopProviders).toHaveLength(0);
            });
            it('multiple providers returned by api => promise resolves to expected', async () => {
                // Arrange
                const provider1 = {
                    companyName: getRandomString(6, 6)
                };
                const provider2 = {
                    companyName: getRandomString(6, 6)
                };

                const responseProviders = {
                    data: {
                        shopProviders: [provider1, provider2]
                    }
                };
                globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(responseProviders));

                // Act
                const result = await store.getTpaProviders();

                // Asserts
                expect(result.data.shopProviders).toHaveLength(2);
                expect(result.data.shopProviders[0]).toBe(provider1);
                expect(result.data.shopProviders[1]).toBe(provider2);
            });
        });
        it('api call throws exception => coverageType none', async () => {
            expect.assertions(3);
            const error = 'get coverage policy info error';

            store.issConfig.isCoverageEnabled = true;
            store.applicationUser.coverageLookupAttempts = 0;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            // Act
            await store.getCoveragePolicyInfo().catch((e) => {
                expect(e).toEqual(error);
            });

            // Asserts
            expect(globalMethods.callHttpClient)
                .toHaveBeenCalledWith(expect.objectContaining({
                    method: endpoints.CoveragePolicyInfo.method,
                    endpoint: endpoints.CoveragePolicyInfo.url
                }));
            expect(store.order.insuranceCoverage.coverageType).toBe(coverageType.NONE);
        });
    });

    describe.each([
        [paymentMethods.CREDIT_CARD],
        [paymentMethods.AFTERPAY],
        [paymentMethods.APPLEPAY],
        [paymentMethods.PAYPAL]
    ])('savePaymentMethodChoice method', (expected) => {
        test(`sets paymentMethod to ${getEnumName(paymentMethods, expected)} when value is ${getEnumName(paymentMethods, expected)}`, () => {
            // Arrange

            // Act
            store.savePaymentMethodChoice(expected);

            // Assert
            expect(store.order.payment.paymentMethod).toBe(expected);
        });
    });

    describe('updatePaypalToken method', () => {
        it('paypalToken is valid when set', () => {
            // Arrange
            const paypalToken = getRandomString(6, 6);

            // Act
            store.updatePaypalToken(paypalToken);

            // Assert
            expect(store.order.payment.paypalToken).toEqual(paypalToken);
        });
    });

    describe.each([
        [true, true],
        [false, false],
        [false, null]
    ])('updateIsItacOptimized', (expected, isItacOptimized) => {
        test(`sets isItacOptimized to ${expected} when passed ${isItacOptimized}`, () => {
            // Arrange
            store.updateIsItacOptimized(isItacOptimized);

            // Act
            const result = store.order.insuranceCoverage.isItacOptimized;

            // Assert
            expect(result).toBe(expected);
        });
    });

    describe('loadSession method', () => {
        let mockDuplicate;
        let mockResponse;

        beforeEach(() => {
            mockDuplicate = {
                referralNumber: getRandomString(10, 10),
                referralDate: new Date().toISOString(),
                correlationId: getRandomGuid()
            };

            mockResponse = {
                data: {
                    customer: {
                        address: {
                            streetAddress: getRandomString(10, 50),
                            streetAddress2: getRandomString(5, 20),
                            city: getRandomString(5, 20),
                            state: getRandomString(2, 2),
                            zipCode: getRandomString(5, 5)
                        },
                        firstName: getRandomString(5, 15),
                        lastName: getRandomString(5, 15),
                        emailAddress: `${getRandomString(5, 10)}@test.com`,
                        homePhone: getRandomString(10, 10),
                        servicePhone: getRandomString(10, 10),
                        alternativePhone: getRandomString(10, 10),
                        isSmsOptIn: getRandomBoolean()
                    },
                    vehicle: {
                        year: getRandomInt(2000, 2024).toString(),
                        make: getRandomString(5, 15),
                        model: getRandomString(5, 15),
                        style: getRandomString(5, 15),
                        carId: getRandomInt(1000, 9999),
                        vin: getRandomString(17, 17),
                        licensePlateNumber: getRandomString(7, 7)
                    },
                    insuranceCoverage: {
                        coverageType: getRandomEnum(coverageType),
                        coverageStatus: getRandomEnum(coverageStatuses),
                        claimNumber: getRandomString(10, 10)
                    },
                    referralNumber: getRandomString(10, 10),
                    referralDate: new Date().toISOString(),
                    referralCorrelationId: getRandomGuid(),
                    referralSequenceNumber: getRandomInt(1, 100),
                    eon: getRandomString(10, 10)
                }
            };

            store.order.parentAccountNumber = getRandomString(6, 6);
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
        });

        it('should call callHttpClient with correct parameters', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(globalMethods.callHttpClient).toHaveBeenCalledWith({
                method: endpoints.LoadSession.method,
                endpoint: endpoints.LoadSession.url,
                payload: {
                    referralNumber: mockDuplicate.referralNumber,
                    referralDate: mockDuplicate.referralDate,
                    parentAccountNumber: store.order.parentAccountNumber,
                    referralCorrelationId: mockDuplicate.correlationId
                }
            });
        });

        it('should return early when response data is null/undefined', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve({ data: null }));
            const originalStreetAddress = store.order.customer.address.streetAddress;

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.customer.address.streetAddress).toBe(originalStreetAddress);
            expect(store.order.loadedFromDupeCheck).toBe(null);
        });

        it('should update customer address fields from response data', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.customer.address.streetAddress).toBe(mockResponse.data.customer.address.streetAddress);
            expect(store.order.customer.address.streetAddress2).toBe(mockResponse.data.customer.address.streetAddress2);
            expect(store.order.customer.address.city).toBe(mockResponse.data.customer.address.city);
            expect(store.order.customer.address.state).toBe(mockResponse.data.customer.address.state);
            expect(store.order.customer.address.zipCode).toBe(mockResponse.data.customer.address.zipCode);
        });

        it('should update contact information from response data', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.contactInfo.firstName).toBe(mockResponse.data.customer.firstName);
            expect(store.order.contactInfo.lastName).toBe(mockResponse.data.customer.lastName);
            expect(store.order.contactInfo.emailAddress).toBe(mockResponse.data.customer.emailAddress);
            expect(store.order.contactInfo.servicePhone).toBe(mockResponse.data.customer.servicePhone);
            expect(store.order.contactInfo.alternativePhone).toBe(mockResponse.data.customer.alternativePhone);
            expect(store.order.contactInfo.requestTextUpdates).toBe(mockResponse.data.customer.isSmsOptIn);
        });

        it('should extract extension from homePhone correctly', async () => {
            // Arrange
            mockResponse.data.customer.homePhone = '12345678901234';
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.contactInfo.homePhone).toBe('1234567890');
            expect(store.order.contactInfo.extension).toBe('1234');
        });

        it('should update vehicle information from response data', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.vehicle.year).toBe(mockResponse.data.vehicle.year);
            expect(store.order.vehicle.make).toBe(mockResponse.data.vehicle.make);
            expect(store.order.vehicle.model).toBe(mockResponse.data.vehicle.model);
            expect(store.order.vehicle.style).toBe(mockResponse.data.vehicle.style);
        });

        it('should update insurance coverage when isPolicyLookupSuccessful is true and insuranceCoverage exists in response', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible; // Make isPolicyLookupSuccessful true
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.insuranceCoverage.coverageType).toBe(mockResponse.data.insuranceCoverage.coverageType);
            expect(store.order.insuranceCoverage.coverageStatus).toBe(mockResponse.data.insuranceCoverage.coverageStatus);
            expect(store.order.insuranceCoverage.claimNumber).toBe(mockResponse.data.insuranceCoverage.claimNumber);
        });

        it('should update insurance coverage from payment.insuranceCoverage when main insuranceCoverage does not exist', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            mockResponse.data.insuranceCoverage = null;
            mockResponse.data.payment = {
                insuranceCoverage: {
                    isVerified: true,
                    claimNumber: getRandomString(10, 10)
                }
            };
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.insuranceCoverage.coverageStatus).toBe(coverageStatuses.VERIFIED);
            expect(store.order.insuranceCoverage.claimNumber).toBe(mockResponse.data.payment.insuranceCoverage.claimNumber);
        });

        it('should update vehicle registration license plate when policy vehicles exist and carId is present', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.policy.vehicles = [
                { id: 1, vin: mockResponse.data.vehicle.vin }
            ];
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.vehicle.registration.licensePlate).toBe(mockResponse.data.vehicle.licensePlateNumber);
        });

        it('should call lookupVehicleByVin and update vehicle when vin matches policy vehicle', async () => {
            // Arrange
            const mockVehicleLookupResponse = {
                data: {
                    carId: getRandomInt(1000, 9999),
                    year: getRandomInt(2000, 2024).toString()
                }
            };
            const policyVehicle = { 
                id: getRandomInt(1, 100),
                vin: mockResponse.data.vehicle.vin,
                deductible: 100,
                repairWaived: false,
                endorsements: ['OEM Approved']
            };

            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.policy.vehicles = [policyVehicle];
            
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));
            store.lookupVehicleByVin = jest.fn().mockReturnValue(Promise.resolve(mockVehicleLookupResponse));
            store.updateVehicle = jest.fn();
            store.updateVehicleCoverage = jest.fn();

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.lookupVehicleByVin).toHaveBeenCalledWith(mockResponse.data.vehicle.vin);
            expect(store.updateVehicle).toHaveBeenCalledWith({
                ...mockVehicleLookupResponse.data,
                policyVehicleId: policyVehicle.id,
                vin: policyVehicle.vin
            });
            expect(store.updateVehicleCoverage).toHaveBeenCalled();
        });

        it('should not call lookupVehicleByVin when policy vehicles array is empty', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.policy.vehicles = [];
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));
            store.lookupVehicleByVin = jest.fn();

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.lookupVehicleByVin).not.toHaveBeenCalled();
        });

        it('should not call lookupVehicleByVin when carId is not present', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.policy.vehicles = [{ id: 1, vin: 'TEST123456789' }];
            mockResponse.data.vehicle.carId = null;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));
            store.lookupVehicleByVin = jest.fn();

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.lookupVehicleByVin).not.toHaveBeenCalled();
        });

        it('should not call lookupVehicleByVin when vin is not present', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.Deductible;
            store.order.policy.vehicles = [{ id: 1, vin: 'TEST123456789' }];
            mockResponse.data.vehicle.vin = null;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));
            store.lookupVehicleByVin = jest.fn();

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.lookupVehicleByVin).not.toHaveBeenCalled();
        });

        it('should not update insurance coverage when isPolicyLookupSuccessful is false', async () => {
            // Arrange
            store.order.insuranceCoverage.coverageType = coverageType.NONE; // Make isPolicyLookupSuccessful false
            const originalCoverageStatus = store.order.insuranceCoverage.coverageStatus;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.insuranceCoverage.coverageStatus).toBe(originalCoverageStatus);
        });

        it('should update referral information from response data', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.referralNumber).toBe(mockResponse.data.referralNumber);
            expect(store.order.referralDate).toBe(mockResponse.data.referralDate);
            expect(store.order.referralCorrelationId).toBe(mockResponse.data.referralCorrelationId);
            expect(store.order.referralSequenceNumber).toBe(mockResponse.data.referralSequenceNumber);
            expect(store.order.eon).toBe(mockResponse.data.eon);
        });

        it('should set loadedFromDupeCheck and loadedSessionClearedPreviousData flags', async () => {
            // Arrange
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.loadedFromDupeCheck).toBe(true);
            expect(store.order.loadedSessionClearedPreviousData).toBe(false);
        });

        it('should handle API error gracefully', async () => {
            // Arrange
            const error = new Error('API Error');
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.reject(error));

            // Act & Assert
            await expect(store.loadSession(mockDuplicate)).rejects.toThrow('API Error');
        });

        it('should handle missing optional fields in response data', async () => {
            // Arrange
            mockResponse.data.customer.address.streetAddress2 = undefined;
            mockResponse.data.customer.alternativePhone = undefined;
            globalMethods.callHttpClient = jest.fn().mockReturnValue(Promise.resolve(mockResponse));

            // Act
            await store.loadSession(mockDuplicate);

            // Assert
            expect(store.order.customer.address.streetAddress2).toBeUndefined();
            expect(store.order.contactInfo.alternativePhone).toBeUndefined();
        });
    });
});
