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";
import { z } from "zod";
import { AGENT_SYSTEM_TURN_PROMPT } from "../sessionStore.js";
const addSystemMessageBodySchema = z.object({
    sessionId: z.string(),
    systemMessage: z.string(),
}).strict();
const getSessionsBodySchema = z.object({
    limit: z.number().int().min(1).max(100).optional(),
}).strict();
const sessionIdBodySchema = z.object({
    sessionId: z.string(),
}).strict();
const createSessionBodySchema = z.object({
    triggerMessage: z.string().optional(),
}).strict();
export function setupSessionEndpoints(ctx, server) {
    server.endpoint({
        method: 'POST',
        path: `/agent/get-sessions`,
        handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
            var _b;
            const data = ctx.parseBody(getSessionsBodySchema, body, response);
            if (!data)
                return;
            const userId = adminUser.pk;
            const limit = (_b = data.limit) !== null && _b !== void 0 ? _b : 20;
            const sessions = yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).list([Filters.EQ(ctx.options.sessionResource.askerIdField, userId)], limit, undefined, [Sorts.DESC(ctx.options.sessionResource.createdAtField)]);
            return {
                sessions: sessions.map((session) => ({
                    sessionId: session[ctx.options.sessionResource.idField],
                    title: session[ctx.options.sessionResource.titleField],
                    timestamp: session[ctx.options.sessionResource.createdAtField],
                })),
            };
        })
    });
    server.endpoint({
        method: 'POST',
        path: `/agent/get-session-info`,
        handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
            const data = ctx.parseBody(sessionIdBodySchema, body, response);
            if (!data)
                return;
            const userId = adminUser.pk;
            const sessionId = data.sessionId;
            const session = yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).get([Filters.EQ(ctx.options.sessionResource.idField, sessionId)]);
            if (!session) {
                return {
                    error: 'Session not found'
                };
            }
            if (session[ctx.options.sessionResource.askerIdField] !== userId) {
                return {
                    error: 'Unauthorized'
                };
            }
            const turns = yield ctx.getSessionTurns(sessionId);
            return {
                session: {
                    sessionId,
                    title: session[ctx.options.sessionResource.titleField],
                    timestamp: session[ctx.options.sessionResource.createdAtField],
                    messages: turns.flatMap(turn => {
                        const messages = [];
                        if (turn.prompt === AGENT_SYSTEM_TURN_PROMPT) {
                            messages.push({
                                text: turn.response,
                                role: 'system',
                            });
                            return messages;
                        }
                        if (turn.prompt) {
                            messages.push({
                                text: turn.prompt,
                                role: 'user',
                            });
                        }
                        if (turn.response && turn.response !== "not_finished") {
                            messages.push({
                                text: turn.response,
                                role: 'assistant',
                            });
                        }
                        return messages;
                    }),
                },
            };
        })
    });
    server.endpoint({
        method: 'POST',
        path: `/agent/create-session`,
        handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
            const data = ctx.parseBody(createSessionBodySchema, body, response);
            if (!data)
                return;
            const triggerMessage = data.triggerMessage;
            const userId = adminUser.pk;
            const title = (triggerMessage === null || triggerMessage === void 0 ? void 0 : triggerMessage.slice(0, 40)) || "New Session";
            const newSession = {
                [ctx.options.sessionResource.idField]: randomUUID(),
                [ctx.options.sessionResource.titleField]: title,
                [ctx.options.sessionResource.askerIdField]: userId,
            };
            const { createdRecord } = yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).create(newSession);
            return {
                sessionId: createdRecord[ctx.options.sessionResource.idField],
                title: createdRecord[ctx.options.sessionResource.titleField],
                timestamp: createdRecord[ctx.options.sessionResource.createdAtField],
                messages: []
            };
        })
    });
    server.endpoint({
        method: 'POST',
        path: `/agent/delete-session`,
        handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
            const data = ctx.parseBody(sessionIdBodySchema, body, response);
            if (!data)
                return;
            const sessionId = data.sessionId;
            const userId = adminUser.pk;
            const session = yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).get([Filters.EQ(ctx.options.sessionResource.idField, sessionId)]);
            if (!session) {
                return {
                    error: 'Session not found'
                };
            }
            if (session[ctx.options.sessionResource.askerIdField] !== userId) {
                return {
                    error: 'Unauthorized'
                };
            }
            yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).delete(sessionId);
            const turns = yield ctx.adminforth.resource(ctx.options.turnResource.resourceId).list([Filters.EQ(ctx.options.turnResource.sessionIdField, sessionId)]);
            yield Promise.all(turns.map(turn => ctx.adminforth.resource(ctx.options.turnResource.resourceId).delete(turn[ctx.options.turnResource.idField])));
            return {
                ok: true
            };
        })
    });
    server.endpoint({
        method: 'POST',
        path: `/agent/add-system-message-to-turns`,
        handler: (_a) => __awaiter(this, [_a], void 0, function* ({ body, adminUser, response }) {
            const data = ctx.parseBody(addSystemMessageBodySchema, body, response);
            if (!data)
                return;
            const session = yield ctx.adminforth.resource(ctx.options.sessionResource.resourceId).get([Filters.EQ(ctx.options.sessionResource.idField, data.sessionId)]);
            if (!session) {
                return {
                    error: 'Session not found'
                };
            }
            if (session[ctx.options.sessionResource.askerIdField] !== adminUser.pk) {
                return {
                    error: 'Unauthorized'
                };
            }
            yield ctx.createSystemTurn(data.sessionId, data.systemMessage);
            return {
                ok: true
            };
        })
    });
}
