"use strict";
/**
 * NightgateAnalyticsService, Aggregated Blockchain Statistics
 *
 * Provides count and average functions over indexed blockchain data.
 * Entity views (BlockStatistics, ContractStatistics) are handled by CDS automatically.
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cds_1 = __importDefault(require("@sap/cds"));
const { SELECT } = cds_1.default.ql;
const midnight_1 = require("#cds-models/midnight");
class NightgateAnalyticsService extends cds_1.default.ApplicationService {
    db;
    async init() {
        this.db = await cds_1.default.connect.to('db');
        this.on('getBlockCount', async () => {
            const result = await this.db.run(SELECT.one.from(midnight_1.Blocks).columns('count(*) as count'));
            return result?.count ?? 0;
        });
        this.on('getTransactionCount', async () => {
            const result = await this.db.run(SELECT.one.from(midnight_1.Transactions).columns('count(*) as count'));
            return result?.count ?? 0;
        });
        this.on('getContractCount', async () => {
            const result = await this.db.run(SELECT.one.from(midnight_1.ContractActions)
                .columns('count(distinct address) as count'));
            return result?.count ?? 0;
        });
        this.on('getAverageTransactionsPerBlock', async () => {
            const blocks = await this.db.run(SELECT.one.from(midnight_1.Blocks).columns('count(*) as count'));
            const txs = await this.db.run(SELECT.one.from(midnight_1.Transactions).columns('count(*) as count'));
            const blockCount = blocks?.count ?? 0;
            if (blockCount === 0)
                return 0;
            return Math.round(((txs?.count ?? 0) / blockCount) * 100) / 100;
        });
        await super.init();
    }
}
exports.default = NightgateAnalyticsService;
