import ScheduledMaintenance from "../../Models/DatabaseModels/ScheduledMaintenance";
import NotFoundException from "../../Types/Exception/NotFoundException";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import ScheduledMaintenanceService from "../Services/ScheduledMaintenanceService";
import UserMiddleware from "../Middleware/UserAuthorization";
import Response from "../Utils/Response";
import BaseAPI from "./BaseAPI";
import CommonAPI from "./CommonAPI";
import AIService from "../Services/AIService";
import ScheduledMaintenanceAIContextBuilder from "../Utils/AI/ScheduledMaintenanceAIContextBuilder";
import JSONFunctions from "../../Types/JSONFunctions";
import Permission from "../../Types/Permission";
export default class ScheduledMaintenanceAPI extends BaseAPI {
    constructor() {
        var _a;
        super(ScheduledMaintenance, ScheduledMaintenanceService);
        // Generate note from AI
        this.router.post(`${(_a = new this.entityType()
            .getCrudApiPath()) === null || _a === void 0 ? void 0 : _a.toString()}/generate-note-from-ai/:scheduledMaintenanceId`, UserMiddleware.getUserMiddleware, async (req, res, next) => {
            try {
                await this.generateNoteFromAI(req, res);
            }
            catch (err) {
                next(err);
            }
        });
    }
    async generateNoteFromAI(req, res) {
        var _a;
        const scheduledMaintenanceIdParam = req.params["scheduledMaintenanceId"];
        if (!scheduledMaintenanceIdParam) {
            throw new BadDataException("Scheduled Maintenance ID is required");
        }
        let scheduledMaintenanceId;
        try {
            scheduledMaintenanceId = new ObjectID(scheduledMaintenanceIdParam);
        }
        catch (_b) {
            throw new BadDataException("Invalid Scheduled Maintenance 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.EditProjectScheduledMaintenance ||
                    p === Permission.CreateScheduledMaintenanceInternalNote ||
                    p === Permission.CreateScheduledMaintenancePublicNote);
            })
            : false;
        if (!hasPermission && !props.isMasterAdmin) {
            throw new BadDataException("You do not have permission to generate notes for this scheduled maintenance.");
        }
        // Get the template and note type from request body
        const template = JSONFunctions.getJSONValueInPath(req.body, "template");
        const noteType = JSONFunctions.getJSONValueInPath(req.body, "noteType") ||
            "internal";
        if (noteType !== "public" && noteType !== "internal") {
            throw new BadDataException("Note type must be 'public' or 'internal'");
        }
        // Get the scheduled maintenance to verify it exists and get the project ID
        const scheduledMaintenance = await this.service.findOneById({
            id: scheduledMaintenanceId,
            select: {
                _id: true,
                projectId: true,
            },
            props,
        });
        if (!scheduledMaintenance || !scheduledMaintenance.projectId) {
            throw new NotFoundException("Scheduled Maintenance not found");
        }
        // Build scheduled maintenance context
        const contextData = await ScheduledMaintenanceAIContextBuilder.buildScheduledMaintenanceContext({
            scheduledMaintenanceId,
        });
        // Format context for note generation
        const aiContext = ScheduledMaintenanceAIContextBuilder.formatScheduledMaintenanceContextForNote(contextData, noteType, template);
        // Generate note using AIService (handles billing and logging)
        const aiLogRequest = {
            projectId: scheduledMaintenance.projectId,
            feature: noteType === "public"
                ? "Scheduled Maintenance Public Note"
                : "Scheduled Maintenance Internal Note",
            scheduledMaintenanceId: scheduledMaintenanceId,
            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=ScheduledMaintenanceAPI.js.map