"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fetchApplicationName = exports.fetchProjectName = exports.fetchOrgName = exports.getUserInfo = exports.buildActivityParams = exports.logActivity = void 0;
const constants_1 = require("../../constants");
const activityLogs_1 = require("../../util/activityLogs");
const logger_1 = __importDefault(require("../../logger"));
const callControlPlaneApi_1 = require("../../util/callContolPlane/callControlPlaneApi");
const database_1 = require("../../database");
const tables_1 = require("../../database/tables");
const drizzle_orm_1 = require("drizzle-orm");
/**
 * Helper function to create activity log
 * @param token - Authentication token
 * @param activityLogParams - Activity log parameters
 */
const logActivity = async (token, activityLogParams) => {
    try {
        const { params, type, project_id, org_id, created_by, updated_by } = activityLogParams;
        await (0, activityLogs_1.createActivityLog)(token, {
            orgId: org_id,
            activityData: {
                params,
                type,
                project_id,
                org_id,
                created_by,
                updated_by,
            },
        });
    }
    catch (error) {
        // Log error but don't throw to prevent breaking the main flow
        logger_1.default.error(`Error creating activity log: ${error}`);
    }
};
exports.logActivity = logActivity;
/**
 * Helper function to build activity log params from template variables
 * @param variables - Object with key-value pairs where keys match template variable names
 * @param ctaTypeMap - Optional map to specify CTA types for specific keys (defaults to common mappings)
 */
const buildActivityParams = (variables, ctaTypeMap) => {
    // Default CTA type mappings based on common keys
    const defaultCTATypeMap = {
        org_id: constants_1.CTAType.ORG_ID,
        org_name: constants_1.CTAType.ORG_ID,
        user_id: constants_1.CTAType.USER_ID,
        user_name: constants_1.CTAType.USER_ID,
        email_id: constants_1.CTAType.EMAIL_ID,
        project_id: constants_1.CTAType.PROJECT_ID,
        project_name: constants_1.CTAType.PROJECT_ID,
        application_id: constants_1.CTAType.APPLICATION_ID,
        application_name: constants_1.CTAType.APPLICATION_ID,
        dataset_id: constants_1.CTAType.DATASET_ID,
        dataset_name: constants_1.CTAType.DATASET_ID,
        prompt_library_id: constants_1.CTAType.PROMPT_LIBRARY_ID,
        prompt_library_name: constants_1.CTAType.PROMPT_LIBRARY_ID,
        alert_condition_id: constants_1.CTAType.ALERT_CONDITION_ID,
        alert_condition_name: constants_1.CTAType.ALERT_CONDITION_ID,
        notification_channel_id: constants_1.CTAType.NOTIFICATION_CHANNEL_ID,
        notification_channel_name: constants_1.CTAType.NOTIFICATION_CHANNEL_ID,
        test_run_id: constants_1.CTAType.TEST_RUN_ID,
        role_id: constants_1.CTAType.ROLE_ID,
        role_name: constants_1.CTAType.ROLE_ID,
        message: constants_1.CTAType.MESSAGE,
        transaction_id: constants_1.CTAType.TRANSACTION_ID,
    };
    const finalCTATypeMap = { ...defaultCTATypeMap, ...ctaTypeMap };
    return Object.entries(variables ?? {})?.map(([key, data]) => {
        const ctaType = data.ctaType || finalCTATypeMap[key] || constants_1.CTAType.MESSAGE;
        const result = {
            cta_type: ctaType,
            key,
            value: data.value,
        };
        if (ctaType === constants_1.CTAType.USER_ID) {
            return result;
        }
        // Add _id if provided, or derive it from value for ID-based CTAs
        if (data._id) {
            result._id = data._id;
        }
        else if (ctaType !== constants_1.CTAType.MESSAGE && data.value) {
            // For ID-based CTAs, use the value as _id if it looks like an ID
            // This handles cases where the value is the actual ID
            result._id = data.value;
        }
        return result;
    });
};
exports.buildActivityParams = buildActivityParams;
/**
 * Helper function to get user info from AuthRequest
 */
const getUserInfo = (req) => {
    const user = req.auth?.payload;
    return {
        userId: user?.id || user?.email || user?._id || '',
        userName: user?.name || user?.email || 'Unknown User',
    };
};
exports.getUserInfo = getUserInfo;
/**
 * Helper function to fetch org name
 */
const fetchOrgName = async (token, orgId) => {
    try {
        if (!token) {
            return '';
        }
        const response = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}`, { method: 'GET' }, token);
        return response?.response?.organization?.name || response?.response?.organization?.org_name || '';
    }
    catch (err) {
        logger_1.default.warn(`Error fetching org name for activity log: ${err}`);
        return '';
    }
};
exports.fetchOrgName = fetchOrgName;
/**
 * Helper function to fetch project name
 */
const fetchProjectName = async (token, orgId, projectId) => {
    try {
        if (!token) {
            return '';
        }
        const response = await (0, callControlPlaneApi_1.callControlPlane)(`/organizations/${orgId}/project/${projectId}`, { method: 'GET' }, token);
        return response?.response?.project?.name || response?.response?.project?.project_name || '';
    }
    catch (err) {
        logger_1.default.warn(`Error fetching project name for activity log: ${err}`);
        return '';
    }
};
exports.fetchProjectName = fetchProjectName;
/**
 * Helper function to fetch application name from database
 */
const fetchApplicationName = async (applicationId) => {
    try {
        if (!applicationId) {
            return '';
        }
        const db = await (0, database_1.getDb)();
        const [application] = await db
            .select({ name: tables_1.applicationsTable.name })
            .from(tables_1.applicationsTable)
            .where((0, drizzle_orm_1.eq)(tables_1.applicationsTable.id, applicationId))
            .limit(1);
        return application?.name || '';
    }
    catch (err) {
        logger_1.default.warn(`Error fetching application name for activity log: ${err}`);
        return '';
    }
};
exports.fetchApplicationName = fetchApplicationName;
//# sourceMappingURL=activityLogService.js.map