import { Dictionary } from "@insite/client-framework/Common/Types";
import { HasFields } from "@insite/client-framework/Types/ContentItemModel";
import { ChildFieldDefinition } from "@insite/client-framework/Types/FieldDefinition";
import { BaseTheme } from "@insite/mobius/globals/baseTheme";

export function validateField(
    fieldDefinition: ChildFieldDefinition,
    item: HasFields,
    advancedFeaturesEnabled?: boolean,
    theme?: Partial<BaseTheme>,
    pageType?: string,
) {
    if (fieldDefinition.isVisible && !fieldDefinition.isVisible(item, advancedFeaturesEnabled, theme, pageType)) {
        return;
    }

    const value = item.fields[fieldDefinition.name];
    let validationError: string | null = null;
    if (fieldDefinition.isRequired && (value === "" || value === undefined || value === null || value?.value === "")) {
        validationError = "A value must be provided.";
    }

    if (!validationError) {
        if (fieldDefinition.regularExpression && !fieldDefinition.regularExpression.test(value)) {
            validationError = "A valid value must be provided.";
        }
    }

    if (!validationError) {
        const validate = fieldDefinition.validate;
        if (validate) {
            validationError = validate(value as never, item); // as never because TypeScript 3.7.0 is confused
        }
    }

    return validationError;
}

export function validateItem(
    fieldDefinitions: ChildFieldDefinition[],
    item: HasFields,
    advancedFeaturesEnabled?: boolean,
    theme?: Partial<BaseTheme>,
    pageType?: string,
) {
    const validationErrors: Dictionary<string> = {};

    for (const fieldDefinition of fieldDefinitions) {
        const validationError = validateField(fieldDefinition, item, advancedFeaturesEnabled, theme, pageType);
        if (validationError) {
            validationErrors[fieldDefinition.name] = validationError;
        }
    }

    return validationErrors;
}
