// frontend/src/lib/models/AgentChat.LocalStorage.ts
// #region AgentChat.LocalStorage [C:2] [TYPE Class] [SEMANTICS agent-chat,persistence,localstorage]
// @ingroup AgentChat
// @BRIEF Browser localStorage persistence for agent chat messages — save/load/clear per conversation.
// @RELATION CALLED_BY -> [AgentChat.Model]
// @RATIONALE Extracted from AgentChat.Model per decomposition gate. Pure utility with no reactive state — plain class, no runes needed.
import type { AgentMessage } from "./AgentChatTypes.js";

export class LocalStorageManager {
  readonly STORAGE_PREFIX = "agentchat:";

  save(
    conversationId: string,
    messages: AgentMessage[],
    partialText: string,
  ): void {
    try {
      const key = `${this.STORAGE_PREFIX}messages:${conversationId}`;
      const data = { messages, partialText, conversationId };
      localStorage.setItem(key, JSON.stringify(data));
    } catch {
      // localStorage may be full or unavailable — silently ignore
    }
  }

  load(
    conversationId: string,
  ): { messages: AgentMessage[]; partialText: string; conversationId: string } | null {
    try {
      const key = `${this.STORAGE_PREFIX}messages:${conversationId}`;
      const raw = localStorage.getItem(key);
      if (!raw) return null;
      const data = JSON.parse(raw);
      if (data?.messages && Array.isArray(data.messages)) {
        return {
          messages: data.messages,
          partialText: data.partialText ?? "",
          conversationId: data.conversationId || conversationId,
        };
      }
      return null;
    } catch {
      return null;
    }
  }

  clear(conversationId: string): void {
    try {
      const key = `${this.STORAGE_PREFIX}messages:${conversationId}`;
      localStorage.removeItem(key);
    } catch {
      // silent
    }
  }
}
// #endregion AgentChat.LocalStorage
