import type { AssistantConversationMessage } from "./api";

const ASSISTANT_THREAD_STORAGE_PREFIX = "powerup.portal.assistant-thread";

interface StoredAssistantThread {
  threadId?: string;
  assistantName?: string;
  messages: AssistantConversationMessage[];
}

function getAssistantThreadStorageKey(tenantId: string, userId: string): string {
  return `${ASSISTANT_THREAD_STORAGE_PREFIX}:${tenantId}:${userId}`;
}

export function loadStoredAssistantThread(tenantId: string, userId: string): StoredAssistantThread | null {
  if (typeof window === "undefined") {
    return null;
  }

  try {
    const rawValue = window.localStorage.getItem(getAssistantThreadStorageKey(tenantId, userId));
    if (!rawValue) {
      return null;
    }
    const parsed = JSON.parse(rawValue) as StoredAssistantThread;
    if (!parsed || !Array.isArray(parsed.messages)) {
      return null;
    }
    const messages = parsed.messages
      .filter((message) => message && (message.role === "user" || message.role === "assistant") && typeof message.content === "string")
      .slice(-40);
    return {
      threadId: typeof parsed.threadId === "string" && parsed.threadId ? parsed.threadId : undefined,
      assistantName: typeof parsed.assistantName === "string" ? parsed.assistantName : undefined,
      messages
    };
  } catch {
    return null;
  }
}

export function storeAssistantThread(
  tenantId: string,
  userId: string,
  thread: { threadId?: string | null; assistantName?: string; messages: AssistantConversationMessage[] }
): void {
  if (typeof window === "undefined") {
    return;
  }

  const payload: StoredAssistantThread = {
    threadId: thread.threadId || undefined,
    assistantName: thread.assistantName,
    messages: thread.messages.slice(-40)
  };
  window.localStorage.setItem(getAssistantThreadStorageKey(tenantId, userId), JSON.stringify(payload));
}

export function clearStoredAssistantThread(tenantId: string, userId: string): void {
  if (typeof window === "undefined") {
    return;
  }

  window.localStorage.removeItem(getAssistantThreadStorageKey(tenantId, userId));
}
