import { ExtendedCookieJar } from "../cookieJar.js";
import { validateOptions as validateLogger } from "./logger.js";
import optionsSchema from "./options.schema.js";
import validateAndCoerceTypes from "../validateAndCoerceTypes.js";
import { getTypedDefinitions } from "../validate/index.js";
const definitions = getTypedDefinitions(optionsSchema);
export function mergeObjects(original, objToMerge) {
    const ownKeys = Reflect.ownKeys(objToMerge);
    for (const key of ownKeys) {
        if (typeof objToMerge[key] === "object") {
            mergeObjects(original[key], objToMerge[key]);
        }
        else {
            original[key] = objToMerge[key];
        }
    }
}
export function validateOptions(options, source = "_setOpts") {
    // Exclude complex types that won't validate properly with json-schema
    // and check later.
    const { cookieJar, logger, fetch, ...simpleOptions } = options;
    // Validation of simple JSON types
    validateAndCoerceTypes({
        object: simpleOptions,
        source,
        type: "options",
        // options: this._opts.validation!,
        options: {
            logErrors: false,
            logOptionsErrors: true,
            allowAdditionalProps: false,
        },
        schemaOrSchemaKey: "#/definitions/YahooFinanceOptions",
        definitions,
        logger: this._opts.logger,
        logObj: this._logObj,
        // versionCheck: this._opts.versionCheck!,
        versionCheck: false,
    });
    // Complex type checks
    if (cookieJar && !(cookieJar instanceof ExtendedCookieJar)) {
        throw new Error("cookieJar must be an instance of ExtendedCookieJar");
    }
    logger && validateLogger(logger);
    if (fetch && typeof fetch !== "function") {
        throw new Error("fetch must be a function");
    }
}
export function setOptions(options) {
    validateOptions.call(this, options);
    mergeObjects(this._opts, options);
}
