"use strict";
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */
/* eslint-disable @typescript-eslint/ban-types */
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const models_1 = require("../models");
const cost_model_1 = require("@graphprotocol/cost-model");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getVariable = (vars, name) => {
    if (vars === null) {
        return undefined;
    }
    else {
        try {
            if (Object.prototype.hasOwnProperty.call(vars, name)) {
                return vars[name];
            }
            else {
                return undefined;
            }
        }
        catch (e) {
            return undefined;
        }
    }
};
const setVariable = (vars, name, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value) => {
    if (vars === null) {
        return { [name]: value };
    }
    else {
        try {
            vars[name] = value;
            return vars;
        }
        catch (e) {
            return vars;
        }
    }
};
exports.default = {
    costModel: ({ deployment }, { models }) => __awaiter(void 0, void 0, void 0, function* () {
        const model = yield models.CostModel.findOne({
            where: { deployment },
        });
        return (model === null || model === void 0 ? void 0 : model.toGraphQL()) || null;
    }),
    costModels: (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    { deployments }, { models }) => __awaiter(void 0, void 0, void 0, function* () {
        const costModels = yield models.CostModel.findAll({
            where: deployments ? { deployment: deployments } : undefined,
            order: [['deployment', 'ASC']],
        });
        return costModels.map((model) => model.toGraphQL());
    }),
    setCostModel: ({ costModel }, { models, features, dai }) => __awaiter(void 0, void 0, void 0, function* () {
        const update = models_1.parseGraphQLCostModel(costModel);
        // Validate cost model
        try {
            const modelForValidation = update.model || 'default => 1;';
            const variablesForValidation = JSON.stringify(update.variables || {});
            yield cost_model_1.compileAsync(modelForValidation, variablesForValidation);
        }
        catch (err) {
            throw new Error(`Invalid cost model or variables: ${err.message}`);
        }
        const [model] = yield models.CostModel.findOrBuild({
            where: { deployment: update.deployment },
        });
        model.deployment = costModel.deployment || model.deployment;
        model.model =
            costModel.model !== null && costModel.model !== undefined
                ? costModel.model
                : model.model;
        // Update the model variables (fall back to current value if unchanged)
        let variables = update.variables || model.variables;
        if (features.injectDai) {
            const oldDai = getVariable(model.variables, 'DAI');
            const newDai = getVariable(update.variables, 'DAI');
            // Inject the latest DAI value if available
            if (dai.valueReady) {
                variables = setVariable(variables, 'DAI', yield dai.value());
            }
            else if (newDai === undefined && oldDai !== undefined) {
                // Otherwise preserve the old DAI value if there is one;
                // this ensures it's never dropped
                variables = setVariable(variables, 'DAI', oldDai);
            }
        }
        // Apply new variables
        model.variables = variables;
        return (yield model.save()).toGraphQL();
    }),
};
//# sourceMappingURL=cost-models.js.map