import IncidentEpisode from "../../Models/DatabaseModels/IncidentEpisode";
import BadDataException from "../../Types/Exception/BadDataException";
import NotFoundException from "../../Types/Exception/NotFoundException";
import ObjectID from "../../Types/ObjectID";
import IncidentEpisodeService from "../Services/IncidentEpisodeService";
import UserMiddleware from "../Middleware/UserAuthorization";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import CommonAPI from "./CommonAPI";
import AIService from "../Services/AIService";
import IncidentEpisodeAIContextBuilder from "../Utils/AI/IncidentEpisodeAIContextBuilder";
import JSONFunctions from "../../Types/JSONFunctions";
import Permission from "../../Types/Permission";
export default class IncidentEpisodeAPI extends BaseAPI {
    constructor() {
        var _a;
        super(IncidentEpisode, IncidentEpisodeService);
        // Generate postmortem from AI
        this.router.post(`${(_a = new this.entityType()
            .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/generate-postmortem-from-ai/:episodeId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.generatePostmortemFromAI(req, res);
            }
            catch (err) {
                next(err);
            }
        });
    }
    async generatePostmortemFromAI(req, res) {
        var _a;
        const episodeIdParam = req.params["episodeId"];
        if (!episodeIdParam) {
            throw new BadDataException("Episode ID is required");
        }
        let episodeId;
        try {
            episodeId = new ObjectID(episodeIdParam);
        }
        catch (_b) {
            throw new BadDataException("Invalid Episode ID");
        }
        const props = await CommonAPI.getDatabaseCommonInteractionProps(req);
        // Verify user has permission to edit the episode
        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.EditIncidentEpisode);
            })
            : false;
        if (!hasPermission && !props.isMasterAdmin) {
            throw new BadDataException("You do not have permission to generate postmortem for this episode. You need to have one of these permissions: Project Owner, Project Admin, Edit Incident Episode.");
        }
        // Get the template from request body if provided
        const template = JSONFunctions.getJSONValueInPath(req.body, "template");
        // Always include workspace messages for comprehensive context
        const includeWorkspaceMessages = true;
        // Get the episode to verify it exists and get the project ID
        const episode = await this.service.findOneById({
            id: episodeId,
            select: {
                _id: true,
                projectId: true,
            },
            props,
        });
        if (!episode || !episode.projectId) {
            throw new NotFoundException("Episode not found");
        }
        // Build episode context
        const contextData = await IncidentEpisodeAIContextBuilder.buildEpisodeContext({
            episodeId,
            includeWorkspaceMessages,
            workspaceMessageLimit: 500,
        });
        // Format context for postmortem generation
        const aiContext = IncidentEpisodeAIContextBuilder.formatEpisodeContextForPostmortem(contextData, template);
        // Generate postmortem using AIService (handles billing and logging)
        const aiLogRequest = {
            projectId: episode.projectId,
            feature: "Incident Episode Postmortem",
            messages: aiContext.messages,
            maxTokens: 8192,
            temperature: 0.7,
        };
        if (props.userId) {
            aiLogRequest.userId = props.userId;
        }
        const response = await AIService.executeWithLogging(aiLogRequest);
        return Response.sendJsonObjectResponse(req, res, {
            postmortemNote: response.content,
        });
    }
}
//# sourceMappingURL=IncidentEpisodeAPI.js.map