/**
 * Copyright 2013-2026 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { camelCase, upperFirst } from 'lodash-es';
import { upperFirstCamelCase } from "./string.js";
export const flatChoices = (choices) => choices.map(choice => (typeof choice === 'string' ? choice : choice.value)).filter(Boolean);
export const derivedPropertyName = (property, value, suffix) => {
    const cleaned = value.replaceAll(/[^a-z0-9-]/gi, '');
    const valueProperty = cleaned.includes('-') ? upperFirstCamelCase(cleaned) : upperFirst(cleaned);
    const camelCaseProperty = camelCase(property);
    return `${camelCaseProperty}${valueProperty}${suffix ?? ''}`;
};
export const applyDerivedProperty = (data, property, possibleValues, { addAny, addNo, defaultValue = 'no' } = {}) => {
    const camelCaseProp = camelCase(property);
    let actualValue = data[camelCaseProp] ?? defaultValue;
    actualValue = actualValue === false && possibleValues.includes('no') ? 'no' : actualValue;
    const flattenedChoices = flatChoices(possibleValues);
    let isAny = false;
    for (const value of flattenedChoices) {
        const isProperty = Array.isArray(actualValue) ? actualValue.includes(value) : actualValue === value;
        data[derivedPropertyName(property, value)] ??= isProperty;
        if (isProperty && value !== 'no') {
            isAny = true;
        }
    }
    if (addAny) {
        data[derivedPropertyName(property, 'any')] ??= isAny;
    }
    if (addNo) {
        if (flattenedChoices.includes('no')) {
            throw new Error('Possible values already include "no"');
        }
        data[derivedPropertyName(property, 'no')] ??= !isAny;
    }
};
export const buildMutateDataForProperty = (property, possibleValues, { prefix = property, suffix = '', array, anyCheck, valCheck = array ? (data, value) => data[property]?.includes(value) ?? false : (data, value) => data[property] === value, } = {}) => {
    return Object.fromEntries([
        ...possibleValues.map(value => [derivedPropertyName(prefix, value, suffix), (data) => valCheck(data, value)]),
        ...(anyCheck ? [[derivedPropertyName(prefix, 'any', suffix), (data) => anyCheck(data[property], possibleValues)]] : []),
    ]);
};
