import UserMiddleware from "../Middleware/UserAuthorization";
import ClusterKeyAuthorization from "../Middleware/ClusterKeyAuthorization";
import AIAgentService from "../Services/AIAgentService";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import PositiveNumber from "../../Types/PositiveNumber";
import AIAgent, { AIAgentConnectionStatus, } from "../../Models/DatabaseModels/AIAgent";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import OneUptimeDate from "../../Types/Date";
import Version from "../../Types/Version";
export default class AIAgentAPI extends BaseAPI {
    constructor() {
        var _a, _b, _c;
        super(AIAgent, AIAgentService);
        // Register Global AI Agent. Custom AI Agent can be registered via dashboard.
        this.router.post(`${(_a = new this.entityType().getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/register`, ClusterKeyAuthorization.isAuthorizedServiceMiddleware, async (req, res, next) => {
            var _a, _b;
            try {
                const data = req.body;
                if (!data["aiAgentKey"]) {
                    return Response.sendErrorResponse(req, res, new BadDataException("aiAgentKey is missing"));
                }
                const aiAgentKey = data["aiAgentKey"];
                const aiAgent = await AIAgentService.findOneBy({
                    query: {
                        key: aiAgentKey,
                        isGlobalAIAgent: true,
                    },
                    select: {
                        _id: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                const defaultDescription = "AI-powered agent that analyzes and resolves code issues, triages incidents and alerts, and helps automate operational workflows.";
                if (aiAgent) {
                    await AIAgentService.updateOneById({
                        id: aiAgent.id,
                        data: {
                            name: data["aiAgentName"] || "Global AI Agent",
                            description: data["aiAgentDescription"] || defaultDescription,
                            lastAlive: OneUptimeDate.getCurrentDate(),
                            connectionStatus: AIAgentConnectionStatus.Connected,
                        },
                        props: {
                            isRoot: true,
                        },
                    });
                    return Response.sendJsonObjectResponse(req, res, {
                        _id: (_a = aiAgent._id) === null || _a === void 0 ? void 0 : _a.toString(),
                        message: "AI Agent already registered",
                    });
                }
                let newAIAgent = new AIAgent();
                newAIAgent.isGlobalAIAgent = true;
                newAIAgent.key = aiAgentKey;
                newAIAgent.name =
                    data["aiAgentName"] || "Global AI Agent";
                newAIAgent.description =
                    data["aiAgentDescription"] || defaultDescription;
                newAIAgent.lastAlive = OneUptimeDate.getCurrentDate();
                newAIAgent.connectionStatus = AIAgentConnectionStatus.Connected;
                newAIAgent.aiAgentVersion = new Version("1.0.0");
                newAIAgent = await AIAgentService.create({
                    data: newAIAgent,
                    props: {
                        isRoot: true,
                    },
                });
                return Response.sendJsonObjectResponse(req, res, {
                    _id: (_b = newAIAgent._id) === null || _b === void 0 ? void 0 : _b.toString(),
                    message: "AI Agent registered successfully",
                });
            }
            catch (err) {
                return next(err);
            }
        });
        // Alive endpoint for AI Agent heartbeat
        this.router.post(`${(_b = new this.entityType().getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/alive`, async (req, res, next) => {
            try {
                const data = req.body;
                if (!data["aiAgentId"] || !data["aiAgentKey"]) {
                    return Response.sendErrorResponse(req, res, new BadDataException("aiAgentId or aiAgentKey is missing"));
                }
                const aiAgentId = new ObjectID(data["aiAgentId"]);
                const aiAgentKey = data["aiAgentKey"];
                const aiAgent = await AIAgentService.findOneBy({
                    query: {
                        _id: aiAgentId.toString(),
                        key: aiAgentKey,
                    },
                    select: {
                        _id: true,
                    },
                    props: {
                        isRoot: true,
                    },
                });
                if (!aiAgent) {
                    return Response.sendErrorResponse(req, res, new BadDataException("Invalid AI Agent ID or AI Agent Key"));
                }
                // Update last alive
                await AIAgentService.updateLastAlive(aiAgentId);
                return Response.sendEmptySuccessResponse(req, res);
            }
            catch (err) {
                next(err);
            }
        });
        this.router.post(`${(_c = new this.entityType().getCrudApiPath()) === null || _c === void 0 ? void 0 : _c.toString()}/global-ai-agents`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                const aiAgents = await AIAgentService.findBy({
                    query: {
                        isGlobalAIAgent: true,
                    },
                    select: {
                        name: true,
                        description: true,
                        lastAlive: true,
                        iconFileId: true,
                        connectionStatus: true,
                    },
                    props: {
                        isRoot: true,
                    },
                    skip: 0,
                    limit: LIMIT_MAX,
                });
                return Response.sendEntityArrayResponse(req, res, aiAgents, new PositiveNumber(aiAgents.length), AIAgent);
            }
            catch (err) {
                next(err);
            }
        });
    }
}
//# sourceMappingURL=AIAgentAPI.js.map