import { IPartsOrQuestionsResponse } from "@business-logic/types/DigitalAPI";
import { ITestData } from "@business-logic/types/ITestData";
import { expect, Response } from "@playwright/test";

export default class ApiResponseInterceptUtil {
    readonly testData: Partial<ITestData>;

    constructor(testData: Partial<ITestData>) {
        this.testData = testData;

        // Bind callback functions to the class instance so 'this' is usable within a callback
        this.handleInterceptResponse = this.handleInterceptResponse.bind(this);
        this.handlePartsOrQuestionsResponse = this.handlePartsOrQuestionsResponse.bind(this);
    }

    async handleInterceptResponse(response: Response) {
        if (!response.url().includes('safelite.io')) {
            return;
        }

        const urlPath = response.url().split('safelite.io')[1]; // get api path
        
        switch(urlPath) {
            case '/parts/api/v1/parts/parts-or-questions':
                await this.handlePartsOrQuestionsResponse(response);
                break;
            //TODO: add validation for other urls in the API
            default:
                break;
        }
        if (response.url().endsWith('/parts/parts-or-questions') && response.status() === 200) {

        }
    }

    async handlePartsOrQuestionsResponse(response: Response) {
        if (this.testData.hasOemEndorsement) {
            const partsRes = (await response.json()) as IPartsOrQuestionsResponse;
            for ( const partOrQuestion of partsRes.partsOrQuestions) {
                for (const part of partOrQuestion.parts) {
                    expect.soft(part.partNumber.endsWith('OEM'), 
                        `handlePartsOrQuestionsResponse>> OEM endorsement was expected, but "${part.partType}" with part number "${part.partNumber}" is not OEM.`
                    ).toEqual(true);
                }
            }
        }
    }
}