import damageLocationsSelected from '@/constants/damage-locations-selected.js';

function getLocationAnswer(damageLocation, locationAnswers) {
    return locationAnswers?.find((answer) => answer.Name === damageLocation);
}

function getGlassPieces(damageLocation, glassToReplace) {
    return glassToReplace?.filter((item) => item.glassLocation === damageLocation);
}

function getWindshieldCopy(answerContent, glassToReplace, isRepair) {
    const windshieldPieces = getGlassPieces(damageLocationsSelected.WINDSHIELD, glassToReplace);
    return isRepair || !!windshieldPieces?.length ? [answerContent?.Text] : [];
}

function getRearCopy(answerContent, glassToReplace) {
    const rearPieces = getGlassPieces(damageLocationsSelected.REAR, glassToReplace);
    return rearPieces?.length ? [answerContent?.Text] : [];
}

function generateBulletedListFromAnswers(answers) {
    const items = answers.map((answer) => `<li>${answer.Text}</li>`);
    return `<ul>${items.join('')}</ul>`;
}

function getSideCopy(location, locationAnswers, damageAnswers, glassToReplace) {
    const sideItems = getGlassPieces(location, glassToReplace);
    const damageAnswersOnOrder = damageAnswers?.filter((answer) =>
        sideItems?.some((glassPiece) => answer.Name === glassPiece.glassName));

    return sideItems?.length
        ? [
            locationAnswers?.Text,
            generateBulletedListFromAnswers(damageAnswersOnOrder)
        ]
        : [];
}

function getDamageDisplayContent(
    locationAnswers,
    driverSideDamageAnswers,
    passengerSideDamageAnswers,
    glassToReplace,
    isRepair
) {
    return [
        ...getWindshieldCopy(
            getLocationAnswer(damageLocationsSelected.WINDSHIELD, locationAnswers),
            glassToReplace,
            isRepair
        ),
        ...getSideCopy(
            damageLocationsSelected.DRIVER,
            getLocationAnswer(damageLocationsSelected.DRIVER, locationAnswers),
            driverSideDamageAnswers,
            glassToReplace
        ),
        ...getSideCopy(
            damageLocationsSelected.PASSENGER,
            getLocationAnswer(damageLocationsSelected.PASSENGER, locationAnswers),
            passengerSideDamageAnswers,
            glassToReplace
        ),
        ...getRearCopy(
            getLocationAnswer(damageLocationsSelected.REAR, locationAnswers),
            glassToReplace
        )
    ];
}

export { getDamageDisplayContent, getLocationAnswer };
