// Add these handlers to: src/gateway/server-methods/sessions.ts
// inside the sessionsHandlers object.
//
// Required imports to add at the top of the file:
//
//   import {
//     listArchivedSessions,
//     updateSessionName,
//     deleteSessionRecord,
//   } from "../../config/sessions/history-db.js";
//   import { initHistoryDbWithMigration } from "../../config/sessions/history-migration.js";
//   import { resolveSessionTranscriptsDirForAgent } from "../../config/sessions/paths.js";
//   import { restoreSessionFromArchive } from "../session-archive.js";
//
// And import the validators from protocol/index.ts:
//   validateSessionsArchivedParams,
//   validateSessionsResumeParams,
//   validateSessionsRenameParams,
//   validateSessionsDeleteArchivedParams,

  "sessions.archived": async ({ params, respond }) => {
    if (!assertValidParams(params, validateSessionsArchivedParams, "sessions.archived", respond)) {
      return;
    }

    const { agentId, limit = 50, offset = 0, search, status = "archived" } = params;
    const config = loadConfig();
    const resolvedAgentId = agentId ?? resolveDefaultAgentId(config);

    try {
      const sessionsDir = resolveSessionTranscriptsDirForAgent(resolvedAgentId);
      const historyDb = initHistoryDbWithMigration(sessionsDir, resolvedAgentId);

      const result = listArchivedSessions(historyDb, {
        agentId: resolvedAgentId,
        limit,
        offset,
        search,
        status,
      });

      respond(true, result, undefined);
    } catch (error) {
      respond(false, undefined, errorShape(ErrorCodes.InternalError, String(error), true));
    }
  },

  "sessions.resume": async ({ params, respond }) => {
    if (!assertValidParams(params, validateSessionsResumeParams, "sessions.resume", respond)) {
      return;
    }

    const { sessionId, agentId } = params;
    const config = loadConfig();
    const resolvedAgentId = agentId ?? resolveDefaultAgentId(config);

    try {
      const sessionsDir = resolveSessionTranscriptsDirForAgent(resolvedAgentId);
      const restored = restoreSessionFromArchive({
        sessionId,
        sessionsDir,
        agentId: resolvedAgentId,
      });

      if (!restored) {
        respond(
          false,
          undefined,
          errorShape(ErrorCodes.NotFound, "Session not found in archive", false),
        );
        return;
      }

      respond(
        true,
        {
          sessionId: restored.sessionId,
          sessionKey: restored.sessionKey,
          displayName: restored.displayName,
          status: restored.status,
        },
        undefined,
      );
    } catch (error) {
      respond(false, undefined, errorShape(ErrorCodes.InternalError, String(error), true));
    }
  },

  "sessions.rename": async ({ params, respond }) => {
    if (!assertValidParams(params, validateSessionsRenameParams, "sessions.rename", respond)) {
      return;
    }

    const { sessionId, displayName, agentId } = params;
    const config = loadConfig();
    const resolvedAgentId = agentId ?? resolveDefaultAgentId(config);

    try {
      const sessionsDir = resolveSessionTranscriptsDirForAgent(resolvedAgentId);
      const historyDb = initHistoryDbWithMigration(sessionsDir, resolvedAgentId);

      updateSessionName(historyDb, sessionId, displayName);
      respond(true, { sessionId, displayName }, undefined);
    } catch (error) {
      respond(false, undefined, errorShape(ErrorCodes.InternalError, String(error), true));
    }
  },

  "sessions.deleteArchived": async ({ params, respond }) => {
    if (!assertValidParams(params, validateSessionsDeleteArchivedParams, "sessions.deleteArchived", respond)) {
      return;
    }

    const { sessionId, agentId, deleteTranscript = false } = params;
    const config = loadConfig();
    const resolvedAgentId = agentId ?? resolveDefaultAgentId(config);

    try {
      const sessionsDir = resolveSessionTranscriptsDirForAgent(resolvedAgentId);
      const historyDb = initHistoryDbWithMigration(sessionsDir, resolvedAgentId);

      const sessionRecord = historyDb
        .prepare(`SELECT * FROM session_history WHERE sessionId = ?`)
        .get(sessionId) as unknown;

      if (!sessionRecord) {
        respond(false, undefined, errorShape(ErrorCodes.NotFound, "Session not found", false));
        return;
      }

      const filePath = (sessionRecord as { filePath?: string }).filePath;
      if (deleteTranscript && filePath && fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }

      deleteSessionRecord(historyDb, sessionId);

      respond(
        true,
        {
          sessionId,
          transcriptDeleted: Boolean(deleteTranscript && filePath),
        },
        undefined,
      );
    } catch (error) {
      respond(false, undefined, errorShape(ErrorCodes.InternalError, String(error), true));
    }
  },
