import TelemetryException from "../../Models/DatabaseModels/TelemetryException";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import BaseModel from "../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
import TelemetryExceptionService from "../Services/TelemetryExceptionService";
import AIAgentTaskTelemetryExceptionService from "../Services/AIAgentTaskTelemetryExceptionService";
import UserMiddleware from "../Middleware/UserAuthorization";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import CommonAPI from "./CommonAPI";
import AIAgentTaskStatus, { AIAgentTaskStatusHelper, } from "../../Types/AI/AIAgentTaskStatus";
import QueryHelper from "../Types/Database/QueryHelper";
export default class TelemetryExceptionAPI extends BaseAPI {
    constructor() {
        var _a, _b, _c;
        super(TelemetryException, TelemetryExceptionService);
        // Create AI Agent Task for an exception
        this.router.post(`${(_a = new this.entityType()
            .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/create-ai-agent-task/:telemetryExceptionId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.createAIAgentTask(req, res);
            }
            catch (err) {
                next(err);
            }
        });
        // Get AI Agent Task for an exception
        this.router.get(`${(_b = new this.entityType()
            .getCrudApiPath()) === null || _b === void 0 ? void 0 : _b.toString()}/get-ai-agent-task/:telemetryExceptionId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.getAIAgentTaskForException(req, res);
            }
            catch (err) {
                next(err);
            }
        });
        /*
         * Aggregated dashboard summary for the Exceptions overview page.
         * Returns counts, top/recent exceptions, and per-service summaries
         * in a single round-trip with one SQL GROUP BY for service aggregation.
         */
        this.router.post(`${(_c = new this.entityType().getCrudApiPath()) === null || _c === void 0 ? void 0 : _c.toString()}/dashboard-summary`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.getDashboardSummary(req, res);
            }
            catch (err) {
                next(err);
            }
        });
    }
    async createAIAgentTask(req, res) {
        const telemetryExceptionIdParam = req.params["telemetryExceptionId"];
        if (!telemetryExceptionIdParam) {
            throw new BadDataException("Telemetry Exception ID is required");
        }
        let telemetryExceptionId;
        try {
            telemetryExceptionId = new ObjectID(telemetryExceptionIdParam);
        }
        catch (_a) {
            throw new BadDataException("Invalid Telemetry Exception ID");
        }
        const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
        // Create the AI Agent Task using the service
        const createdTask = await this.service.createAIAgentTaskForException({
            telemetryExceptionId,
            props,
        });
        return Response.sendJsonObjectResponse(req, res, {
            aiAgentTaskId: createdTask.id.toString(),
        });
    }
    async getAIAgentTaskForException(req, res) {
        var _a;
        const telemetryExceptionIdParam = req.params["telemetryExceptionId"];
        if (!telemetryExceptionIdParam) {
            throw new BadDataException("Telemetry Exception ID is required");
        }
        let telemetryExceptionId;
        try {
            telemetryExceptionId = new ObjectID(telemetryExceptionIdParam);
        }
        catch (_b) {
            throw new BadDataException("Invalid Telemetry Exception ID");
        }
        const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
        // Find the most recent AI agent task for this exception that is not completed or errored
        const taskLink = await AIAgentTaskTelemetryExceptionService.findOneBy({
            query: {
                telemetryExceptionId: telemetryExceptionId,
                aiAgentTask: {
                    status: QueryHelper.notIn([
                        AIAgentTaskStatus.Completed,
                        AIAgentTaskStatus.Error,
                    ]),
                },
            },
            select: {
                _id: true,
                aiAgentTaskId: true,
                aiAgentTask: {
                    _id: true,
                    status: true,
                    statusMessage: true,
                    createdAt: true,
                },
            },
            props,
        });
        if (!taskLink || !taskLink.aiAgentTask) {
            return Response.sendJsonObjectResponse(req, res, {
                hasActiveTask: false,
                aiAgentTask: null,
            });
        }
        const task = taskLink.aiAgentTask;
        return Response.sendJsonObjectResponse(req, res, {
            hasActiveTask: true,
            aiAgentTask: {
                _id: (_a = task.id) === null || _a === void 0 ? void 0 : _a.toString(),
                status: task.status,
                statusMessage: task.statusMessage,
                statusTitle: task.status
                    ? AIAgentTaskStatusHelper.getTitle(task.status)
                    : undefined,
                statusDescription: task.status
                    ? AIAgentTaskStatusHelper.getDescription(task.status)
                    : undefined,
                createdAt: task.createdAt,
            },
        });
    }
    async getDashboardSummary(req, res) {
        const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
        const summary = await this.service.getDashboardSummary(props);
        const topExceptionsJson = BaseModel.toJSONArray(summary.topExceptions, TelemetryException);
        const recentExceptionsJson = BaseModel.toJSONArray(summary.recentExceptions, TelemetryException);
        const serviceSummariesJson = summary.serviceSummaries.map((entry) => {
            /*
             * serviceId is polymorphic; the client resolves the display name
             * per serviceType (no Service relation to serialize anymore).
             */
            return {
                primaryEntityId: entry.primaryEntityId,
                primaryEntityType: entry.primaryEntityType,
                unresolvedCount: entry.unresolvedCount,
                totalOccurrences: entry.totalOccurrences,
            };
        });
        return Response.sendJsonObjectResponse(req, res, {
            unresolvedCount: summary.unresolvedCount,
            resolvedCount: summary.resolvedCount,
            archivedCount: summary.archivedCount,
            topExceptions: topExceptionsJson,
            recentExceptions: recentExceptionsJson,
            serviceSummaries: serviceSummariesJson,
        });
    }
}
//# sourceMappingURL=TelemetryExceptionAPI.js.map