"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.FinancialIndexesService = exports.EFinancialIndex = void 0;
const axios_1 = __importDefault(require("axios"));
const decimal_js_1 = __importDefault(require("decimal.js"));
const FinancialIndexes_model_1 = require("../models/FinancialIndexes.model");
var EFinancialIndex;
(function (EFinancialIndex) {
    EFinancialIndex["PRIME_RATE"] = "PRIME_RATE";
})(EFinancialIndex || (exports.EFinancialIndex = EFinancialIndex = {}));
class FinancialIndexesService {
    config;
    constructor(config) {
        this.config = config;
    }
    async getFinancialAllIndexes(indexName) {
        return FinancialIndexes_model_1.FinancialIndexesModel.aggregate([
            {
                $match: {
                    'name': indexName,
                },
            }, {
                $sort: {
                    'date': -1,
                },
            },
        ]);
    }
    async getFinancialIndexValue(indexName, date = new Date()) {
        const indexes = await FinancialIndexes_model_1.FinancialIndexesModel.aggregate([
            {
                $match: {
                    'name': indexName,
                    'date': { $lte: date },
                },
            }, {
                $sort: {
                    'date': -1,
                },
            }, {
                $limit: 1,
            },
        ]);
        if (!indexes.length) {
            return null;
        }
        return indexes[0].value;
    }
    async getAllFinancialIndexes(date = new Date()) {
        const indexes = await FinancialIndexes_model_1.FinancialIndexesModel.aggregate([
            {
                $match: {
                    'date': { $lte: date },
                },
            }, {
                $sort: {
                    'date': 1,
                },
            },
        ]);
        if (!indexes.length) {
            return null;
        }
        return indexes;
    }
    async getAllFinancialIndexesWithHistory(date = new Date()) {
        // TODO can remove from here
        const historyData = [
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2018, 2, 22),
                value: 0.0475,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2018, 5, 14),
                value: 0.05,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2018, 8, 27),
                value: 0.0525,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2018, 11, 20),
                value: 0.055,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2019, 5, 31),
                value: 0.0525,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2019, 8, 18),
                value: 0.05,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2019, 9, 30),
                value: 0.0475,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2020, 2, 3),
                value: 0.0425,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2020, 2, 15),
                value: 0.0325,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 2, 16),
                value: 0.035,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 4, 4),
                value: 0.04,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 5, 15),
                value: 0.0475,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 6, 27),
                value: 0.055,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 8, 21),
                value: 0.0625,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 10, 2),
                value: 0.07,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2022, 11, 14),
                value: 0.075,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2023, 1, 1),
                value: 0.0775,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2023, 2, 22),
                value: 0.08,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2023, 4, 3),
                value: 0.0825,
            },
            {
                name: EFinancialIndex.PRIME_RATE,
                date: new Date(2023, 6, 26),
                value: 0.085,
            },
        ];
        console.log({ historyData });
        await this.cleanIndexes(EFinancialIndex.PRIME_RATE);
        await Promise.all(historyData.map(async (data) => {
            await this.createIndex(data);
        }));
        // TODO to here
        const indexes = await FinancialIndexes_model_1.FinancialIndexesModel.aggregate([
            {
                $match: {
                    'date': { $lte: date },
                },
            }, {
                $sort: {
                    'date': -1,
                },
            },
        ]);
        if (!indexes.length) {
            return null;
        }
        return indexes;
    }
    async createIndex(index) {
        const newIndex = new FinancialIndexes_model_1.FinancialIndexesModel(index);
        await newIndex.save();
    }
    async deleteIndex(indexId) {
        await FinancialIndexes_model_1.FinancialIndexesModel.findByIdAndDelete(indexId);
    }
    async cleanIndexes(index) {
        await FinancialIndexes_model_1.FinancialIndexesModel.deleteMany({ name: index });
    }
    async updatePrimeRate() {
        const currentPrimeRate = await this.getFinancialIndexValue(EFinancialIndex.PRIME_RATE);
        const primeRate = await this.getPrimeRate();
        if (currentPrimeRate === primeRate) {
            return;
        }
        await this.createIndex({ date: new Date, value: primeRate, name: EFinancialIndex.PRIME_RATE });
    }
    async getPrimeRate() {
        const FRED_API_URL = 'https://api.stlouisfed.org/fred/series/observations';
        try {
            const response = await axios_1.default.get(FRED_API_URL, {
                params: {
                    series_id: 'DPRIME',
                    api_key: this.config.apiKey,
                    file_type: 'json',
                    sort_order: 'desc',
                    limit: 1,
                },
            });
            const observations = response.data.observations;
            if (observations && observations.length > 0) {
                const latestObservation = observations[0];
                return new decimal_js_1.default(latestObservation.value).div(100).toNumber();
            }
            else {
                console.log('No observations found.');
                return null;
            }
        }
        catch (error) {
            console.error('Error fetching Prime Rate from FRED API:', error.message);
            return null;
        }
    }
}
exports.FinancialIndexesService = FinancialIndexesService;
