var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Filters, Sorts } from "adminforth";
import { randomUUID } from "crypto";
export const AGENT_SYSTEM_TURN_PROMPT = "__adminforth_system_message__";
export class AgentSessionStore {
    constructor(getAdminforth, options) {
        this.getAdminforth = getAdminforth;
        this.options = options;
    }
    createNewTurn(sessionId, prompt, response) {
        return __awaiter(this, void 0, void 0, function* () {
            const turnId = randomUUID();
            const turnRecord = {
                [this.options.turnResource.idField]: turnId,
                [this.options.turnResource.sessionIdField]: sessionId,
                [this.options.turnResource.promptField]: prompt,
                [this.options.turnResource.responseField]: response !== null && response !== void 0 ? response : "not_finished",
            };
            const newTurn = yield this.getAdminforth().resource(this.options.turnResource.resourceId).create(turnRecord);
            return newTurn.createdRecord[this.options.turnResource.idField];
        });
    }
    createSystemTurn(sessionId, systemMessage) {
        return __awaiter(this, void 0, void 0, function* () {
            const turnId = randomUUID();
            const turnRecord = {
                [this.options.turnResource.idField]: turnId,
                [this.options.turnResource.sessionIdField]: sessionId,
                [this.options.turnResource.promptField]: AGENT_SYSTEM_TURN_PROMPT,
                [this.options.turnResource.responseField]: systemMessage,
            };
            const newTurn = yield this.getAdminforth().resource(this.options.turnResource.resourceId).create(turnRecord);
            return newTurn.createdRecord[this.options.turnResource.idField];
        });
    }
    getSessionTurns(sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            const turns = yield this.getAdminforth().resource(this.options.turnResource.resourceId).list([Filters.EQ(this.options.turnResource.sessionIdField, sessionId)], undefined, undefined, [Sorts.ASC(this.options.turnResource.createdAtField)]);
            return turns.map(turn => ({
                prompt: turn[this.options.turnResource.promptField],
                response: turn[this.options.turnResource.responseField],
            }));
        });
    }
    getPreviousUserMessages(sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            const turns = yield this.getAdminforth().resource(this.options.turnResource.resourceId).list([Filters.EQ(this.options.turnResource.sessionIdField, sessionId)], 2, undefined, [Sorts.DESC(this.options.turnResource.createdAtField)]);
            return turns
                .reverse()
                .filter((turn) => turn[this.options.turnResource.promptField] !== AGENT_SYSTEM_TURN_PROMPT)
                .map((turn) => ({
                text: turn[this.options.turnResource.promptField],
            }));
        });
    }
    getLatestTurn(sessionId) {
        return __awaiter(this, void 0, void 0, function* () {
            const turns = yield this.getAdminforth().resource(this.options.turnResource.resourceId).list([Filters.EQ(this.options.turnResource.sessionIdField, sessionId)], 1, undefined, [Sorts.DESC(this.options.turnResource.createdAtField)]);
            return turns[0];
        });
    }
    getChatSurfaceSessionId(incoming) {
        return `${incoming.surface}:${incoming.externalConversationId}`;
    }
    getOrCreateChatSurfaceSession(incoming, adminUser) {
        return __awaiter(this, void 0, void 0, function* () {
            const sessionId = this.getChatSurfaceSessionId(incoming);
            const sessionResource = this.getAdminforth().resource(this.options.sessionResource.resourceId);
            const session = yield sessionResource.get([Filters.EQ(this.options.sessionResource.idField, sessionId)]);
            if (session) {
                return sessionId;
            }
            yield sessionResource.create({
                [this.options.sessionResource.idField]: sessionId,
                [this.options.sessionResource.titleField]: incoming.prompt.slice(0, 40) || "New Session",
                [this.options.sessionResource.askerIdField]: adminUser.pk,
            });
            return sessionId;
        });
    }
}
