import Alert from "../../Models/DatabaseModels/Alert";
import NotFoundException from "../../Types/Exception/NotFoundException";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import AlertService from "../Services/AlertService";
import UserMiddleware from "../Middleware/UserAuthorization";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import CommonAPI from "./CommonAPI";
import AIService from "../Services/AIService";
import AlertAIContextBuilder from "../Utils/AI/AlertAIContextBuilder";
import JSONFunctions from "../../Types/JSONFunctions";
import Permission from "../../Types/Permission";
export default class AlertAPI extends BaseAPI {
    constructor() {
        var _a;
        super(Alert, AlertService);
        // Generate note from AI
        this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/generate-note-from-ai/:alertId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.generateNoteFromAI(req, res);
            }
            catch (err) {
                next(err);
            }
        });
    }
    async generateNoteFromAI(req, res) {
        var _a;
        const alertIdParam = req.params["alertId"];
        if (!alertIdParam) {
            throw new BadDataException("Alert ID is required");
        }
        let alertId;
        try {
            alertId = new ObjectID(alertIdParam);
        }
        catch (_b) {
            throw new BadDataException("Invalid Alert ID");
        }
        const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
        // Verify user has permission
        const permissions = (_a = props
            .userTenantAccessPermission) === null || _a === void 0 ? void 0 : _a["permissions"];
        const hasPermission = permissions
            ? permissions.some((p) => {
                return (p === Permission.ProjectOwner ||
                    p === Permission.ProjectAdmin ||
                    p === Permission.EditAlert ||
                    p === Permission.CreateAlertInternalNote);
            })
            : false;
        if (!hasPermission && !props.isMasterAdmin) {
            throw new BadDataException("You do not have permission to generate notes for this alert.");
        }
        // Get the template from request body
        const template = JSONFunctions.getJSONValueInPath(req.body, "template");
        // Get the alert to verify it exists and get the project ID
        const alert = await this.service.findOneById({
            id: alertId,
            select: {
                _id: true,
                projectId: true,
            },
            props,
        });
        if (!alert || !alert.projectId) {
            throw new NotFoundException("Alert not found");
        }
        // Build alert context
        const contextData = await AlertAIContextBuilder.buildAlertContext({
            alertId,
        });
        // Format context for note generation
        const aiContext = AlertAIContextBuilder.formatAlertContextForNote(contextData, template);
        // Generate note using AIService (handles billing and logging)
        const aiLogRequest = {
            projectId: alert.projectId,
            feature: "Alert Internal Note",
            alertId: alertId,
            messages: aiContext.messages,
            maxTokens: 4096,
            temperature: 0.7,
        };
        if (props.userId) {
            aiLogRequest.userId = props.userId;
        }
        const response = await AIService.executeWithLogging(aiLogRequest);
        return Response.sendJsonObjectResponse(req, res, {
            note: response.content,
        });
    }
}
//# sourceMappingURL=AlertAPI.js.map