"use strict";
// this file is the setup file which will run at the start of each deployment
// this can also be triggered from api if something needs to be reset or reinitialized
Object.defineProperty(exports, "__esModule", { value: true });
exports.Setup = void 0;
const promises_1 = require("node:fs/promises");
const ApiHandler_1 = require("./ApiHandler");
const staticPath_1 = require("../utils/staticPath");
class Setup {
    constructor(baseUrl = "https://zap.dzap.io/v1", outputFilePath) {
        this.apiHandler = new ApiHandler_1.ApiHandler(baseUrl);
        this.outputFilePath = outputFilePath !== null && outputFilePath !== void 0 ? outputFilePath : (0, staticPath_1.resolveWritableStaticFilePath)("defi_providers.json");
    }
    async loadProviderList() {
        const response = await this.apiHandler.get("/config/providers");
        const providers = this.extractProviders(response);
        if (Object.keys(providers).length === 0) {
            throw new Error("No providers received from /config/providers.");
        }
        await (0, promises_1.writeFile)(this.outputFilePath, JSON.stringify({ defiProviders: providers }, null, 2), "utf-8");
        return providers;
    }
    extractProviders(response) {
        if (!response || typeof response !== "object") {
            throw new Error("Invalid provider response from /config/providers.");
        }
        const rawProviderData = this.getRawProviderData(response);
        const providers = {};
        for (const [providerKey, providerValue] of Object.entries(rawProviderData)) {
            if (!this.isProviderLike(providerValue)) {
                continue;
            }
            providers[providerKey] = {
                id: typeof providerValue.id === "string" && providerValue.id.length > 0
                    ? providerValue.id
                    : providerKey,
                name: typeof providerValue.name === "string" && providerValue.name.length > 0
                    ? providerValue.name
                    : providerKey,
                icon: typeof providerValue.icon === "string" ? providerValue.icon : "",
                supportedChainIds: Array.isArray(providerValue.supportedChainIds)
                    ? providerValue.supportedChainIds.filter((chainId) => Number.isInteger(chainId))
                    : [],
            };
        }
        return providers;
    }
    getRawProviderData(response) {
        if ("data" in response &&
            response.data &&
            typeof response.data === "object" &&
            !Array.isArray(response.data)) {
            return response.data;
        }
        return response;
    }
    isProviderLike(value) {
        return value !== null && typeof value === "object" && !Array.isArray(value);
    }
}
exports.Setup = Setup;
