"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApplicationListWithMonitoring = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const getApplicationListWithMonitoring = async (req, res) => {
    try {
        const { projectId, page = 1, limit = 10, search, archived_data_required = 'true', ensureApplicationId: ensureApplicationIdRaw, } = req.query;
        const ensureApplicationId = typeof ensureApplicationIdRaw === 'string' && ensureApplicationIdRaw.trim() !== ''
            ? ensureApplicationIdRaw.trim()
            : null;
        const parsedLimit = Number(limit);
        const parsedPage = Number(page);
        const offset = (parsedPage - 1) * parsedLimit;
        const includeArchived = archived_data_required === 'true';
        const db = await (0, database_1.getDb)();
        const applicationFilters = [];
        const allApplicationsFilters = [];
        if (projectId) {
            applicationFilters.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId));
            allApplicationsFilters.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId));
        }
        if (search && typeof search === 'string' && search.trim() !== '') {
            applicationFilters.push((0, drizzle_orm_1.or)((0, drizzle_orm_1.ilike)(tables_1.applicationsTable.name, `%${search}%`), (0, drizzle_orm_1.ilike)(tables_1.applicationsTable.description, `%${search}%`)));
        }
        // Add archived filter if needed
        if (!includeArchived) {
            applicationFilters.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.is_archived, false));
            allApplicationsFilters.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.is_archived, false));
        }
        // const monitoringFilters = or(
        //   and(
        //     sql`${pulseMonitoringTable.metrics} IS NOT NULL`,
        //     sql`jsonb_array_length(${pulseMonitoringTable.metrics}) > 0`,
        //   ),
        //   and(
        //     sql`${pulseMonitoringTable.pluginsByCategory} IS NOT NULL`,
        //     sql`jsonb_typeof(${pulseMonitoringTable.pluginsByCategory}) = 'object'`,
        //     sql`${pulseMonitoringTable.pluginsByCategory} != '{}'::jsonb`,
        //   ),
        // );
        const allFilters = [...applicationFilters];
        const monitoringSelect = {
            id: tables_1.applicationsTable.id,
            name: tables_1.applicationsTable.name,
            createdAt: tables_1.applicationsTable.createdAt,
            projectId: tables_1.applicationsTable.projectId,
            is_archived: tables_1.applicationsTable.is_archived,
            monitoringId: tables_1.pulseMonitoringTable.id,
            metrics: tables_1.pulseMonitoringTable.metrics,
            pluginsByCategory: tables_1.pulseMonitoringTable.pluginsByCategory,
            isAgentic: tables_1.applicationsTable.isAgentic,
            hasVectorDb: tables_1.applicationsTable.hasVectorDb,
        };
        let applicationRows = await db
            .select(monitoringSelect)
            .from(tables_1.applicationsTable)
            .innerJoin(tables_1.pulseMonitoringTable, (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, tables_1.pulseMonitoringTable.applicationId))
            .where((0, drizzle_orm_1.and)(...allFilters))
            .orderBy(tables_1.applicationsTable.is_archived, // false first, then true
        tables_1.applicationsTable.createdAt // within each group, order by createdAt
        )
            .limit(parsedLimit)
            .offset(offset);
        if (ensureApplicationId &&
            projectId &&
            !applicationRows.some((a) => String(a.id) === ensureApplicationId)) {
            const extraFilters = [
                (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, ensureApplicationId),
                (0, drizzle_orm_1.eq)(tables_1.applicationsTable.projectId, projectId),
            ];
            if (!includeArchived) {
                extraFilters.push((0, drizzle_orm_1.eq)(tables_1.applicationsTable.is_archived, false));
            }
            const extraRows = await db
                .select(monitoringSelect)
                .from(tables_1.applicationsTable)
                .innerJoin(tables_1.pulseMonitoringTable, (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, tables_1.pulseMonitoringTable.applicationId))
                .where((0, drizzle_orm_1.and)(...extraFilters))
                .limit(1);
            if (extraRows[0]) {
                applicationRows = [extraRows[0], ...applicationRows];
            }
        }
        // Process applications to add audio-metrics field
        const processedApplications = applicationRows.map((app) => {
            const audioMetrics = [];
            if (app.metrics && Array.isArray(app.metrics)) {
                // Define the audio metrics we're looking for
                const audioMetricTypes = [
                    'audio-background-noise',
                    'audio-call-category',
                    'audio-call-outcome',
                    'audio-language',
                    'audio-talk-to-listen-ratio',
                    'audio-agent-response-time',
                    'audio-sentiment',
                ];
                // Extract unique audio metric types from the metrics array
                app.metrics.forEach((metric) => {
                    if (metric &&
                        typeof metric === 'object' &&
                        metric.type &&
                        audioMetricTypes.includes(metric.type) &&
                        !audioMetrics.includes(metric.type)) {
                        audioMetrics.push(metric.type);
                    }
                });
            }
            const metricsArray = app.metrics?.map((metric) => metric.type ?? '');
            const pluginsArray = Object.values(app?.pluginsByCategory ?? {}).flatMap((v) => v);
            const isAgentic = Boolean(app?.isAgentic);
            const hasVectorDb = Boolean(app?.hasVectorDb);
            return {
                ...app,
                metrics: metricsArray ?? [],
                pluginsArray: pluginsArray ?? [],
                'audio-metrics': audioMetrics,
                isAgentic,
                hasVectorDb,
            };
        });
        const totalCount = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.applicationsTable)
            .innerJoin(tables_1.pulseMonitoringTable, (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, tables_1.pulseMonitoringTable.applicationId))
            .where((0, drizzle_orm_1.and)(...allFilters))
            .then((result) => Number(result[0]?.count));
        const allCountFilters = [...allApplicationsFilters];
        const allCount = await db
            .select({ count: (0, drizzle_orm_1.sql) `count(*)` })
            .from(tables_1.applicationsTable)
            .innerJoin(tables_1.pulseMonitoringTable, (0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, tables_1.pulseMonitoringTable.applicationId))
            .where((0, drizzle_orm_1.and)(...allCountFilters))
            .then((result) => Number(result[0]?.count));
        res.json({
            success: true,
            data: {
                applications: processedApplications,
                pagination: {
                    allTotal: allCount,
                    total: totalCount,
                    page: parsedPage,
                    limit: parsedLimit,
                    totalPages: Math.ceil(totalCount / parsedLimit),
                },
            },
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching applications with monitoring: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch applications with monitoring',
        });
    }
};
exports.getApplicationListWithMonitoring = getApplicationListWithMonitoring;
//# sourceMappingURL=get-application-list-with-monitoring.js.map