var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import DatabaseService from "./DatabaseService";
import Model from "../../Models/DatabaseModels/AIAgentTask";
import BadDataException from "../../Types/Exception/BadDataException";
import AIAgentService from "./AIAgentService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import Semaphore from "../Infrastructure/Semaphore";
import SortOrder from "../../Types/BaseDatabase/SortOrder";
import logger from "../Utils/Logger";
import OneUptimeDate from "../../Types/Date";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        // If no aiAgentId is provided, assign one automatically
        if (!createBy.data.aiAgentId) {
            createBy.data.aiAgentId = await this.getDefaultAgentId(createBy);
        }
        else {
            // Validate the provided aiAgentId
            await this.validateAgentBelongsToProject(createBy);
        }
        // Generate task number
        if (!createBy.data.projectId) {
            throw new BadDataException("Project ID is required to create an AI Agent Task");
        }
        const projectId = createBy.data.projectId;
        let mutex = null;
        try {
            mutex = await Semaphore.lock({
                key: projectId.toString(),
                namespace: "AIAgentTaskService.task-create",
                lockTimeout: 15000,
                acquireTimeout: 20000,
            });
            logger.debug("Mutex acquired - AIAgentTaskService.task-create " +
                projectId.toString() +
                " at " +
                OneUptimeDate.getCurrentDateAsFormattedString());
        }
        catch (err) {
            logger.debug("Mutex acquire failed - AIAgentTaskService.task-create " +
                projectId.toString() +
                " at " +
                OneUptimeDate.getCurrentDateAsFormattedString());
            logger.error(err);
        }
        try {
            const taskNumberForThisTask = (await this.getExistingTaskNumberForProject({
                projectId: projectId,
            })) + 1;
            createBy.data.taskNumber = taskNumberForThisTask;
        }
        finally {
            if (mutex) {
                await Semaphore.release(mutex);
            }
        }
        return { createBy, carryForward: null };
    }
    async getExistingTaskNumberForProject(data) {
        // get last task number.
        const lastTask = await this.findOneBy({
            query: {
                projectId: data.projectId,
            },
            select: {
                taskNumber: true,
            },
            sort: {
                createdAt: SortOrder.Descending,
            },
            props: {
                isRoot: true,
            },
        });
        if (!lastTask) {
            return 0;
        }
        return lastTask.taskNumber ? Number(lastTask.taskNumber) : 0;
    }
    async getDefaultAgentId(createBy) {
        if (!createBy.data.projectId) {
            throw new BadDataException("Project ID is required to assign an AI Agent");
        }
        // Try to get the default agent for the project (or global fallback)
        const agent = await AIAgentService.getAIAgentForProject(createBy.data.projectId);
        if (!agent || !agent.id) {
            throw new BadDataException("No AI Agent available. Please configure an AI Agent for this project or ensure a global AI Agent is available.");
        }
        return agent.id;
    }
    async validateAgentBelongsToProject(createBy) {
        if (!createBy.data.aiAgentId || !createBy.data.projectId) {
            return;
        }
        const agent = await AIAgentService.findOneById({
            id: createBy.data.aiAgentId,
            select: {
                _id: true,
                projectId: true,
                isGlobalAIAgent: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!agent) {
            throw new BadDataException("AI Agent not found");
        }
        // Allow if it's a global agent
        if (agent.isGlobalAIAgent) {
            return;
        }
        // Allow if the agent belongs to the same project
        if (agent.projectId &&
            agent.projectId.toString() === createBy.data.projectId.toString()) {
            return;
        }
        // Reject if the agent belongs to a different project
        throw new BadDataException("The specified AI Agent does not belong to this project. Please use an AI Agent from your project or a global AI Agent.");
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getExistingTaskNumberForProject", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getDefaultAgentId", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "validateAgentBelongsToProject", null);
export default new Service();
//# sourceMappingURL=AIAgentTaskService.js.map