import type {
    IConfigurationsFlattenedKeys,
    IPreferencesInput,
    IPreferencesOpenOptionsInput,
    IConfigurationOverridesInput,
} from 'common';
import { ConfigurationTarget } from 'common';
import { useSetting as usePlatformSetting } from '@adminide-stack/platform-client';

export interface ISettingsVariable {
    overrides?: IConfigurationOverridesInput;
    configKey: IConfigurationsFlattenedKeys;
    options?: IPreferencesOpenOptionsInput;
    skip?: boolean;
}

interface IResponse {
    data?: {
        resolveConfiguration?: unknown;
    };
    loading: boolean;
    error?: unknown;
    preferencesInput?: IPreferencesInput;
    updateConfiguration?: ({
        updateKey,
        value,
        updateOverrides,
        target,
    }: {
        updateKey?: string;
        value: string | boolean | number;
        updateOverrides?: IConfigurationOverridesInput;
        target?: ConfigurationTarget;
    }) => Promise<unknown>;
    refetch?: Function;
    [key: string]: unknown;
}

/**
 * Provides configuration for Organization and OrganizationResources. By default, it provides Organization configuration.
 * If you need `resource` level configuration then, you need to provide resource URI in `overrides`.
 * @param baseOptions
 */
export const useSetting = (settingsVariable: ISettingsVariable): IResponse => {
    const { data, updateConfiguration, ...remaining } = usePlatformSetting(settingsVariable as any);

    return {
        data: data === undefined ? undefined : { resolveConfiguration: data },
        ...remaining,
        updateConfiguration: ({ value, updateKey, updateOverrides, target }) => {
            return updateConfiguration?.({
                value,
                updateKey,
                updateOverrides,
                target,
            });
        },
    };
};
