export type ChatRole = "user" | "assistant";

export type ChatAttachment = {
  filename: string;
  mediaType: string;
  url: string;
  storagePath?: string | null;
};

export type ChatMessage = {
  id: string;
  role: ChatRole;
  text: string;
  attachments: ChatAttachment[];
  createdAt: number;
  metadata?: Record<string, unknown>;
};

export type ChatSession = {
  id: string;
  title: string;
  messages: ChatMessage[];
  createdAt: number;
  updatedAt: number;
};

const STORAGE_PREFIX = "glm-cotizador-chats-v2";

function storageKey(userId: string) {
  return `${STORAGE_PREFIX}:${userId}`;
}

export function createId() {
  return Math.random().toString(36).slice(2, 11);
}

export function chatTitleFromMessages(messages: ChatMessage[]) {
  const firstUserMessage = messages.find((message) => message.role === "user");
  const raw =
    firstUserMessage?.text.trim() ||
    firstUserMessage?.attachments[0]?.filename?.trim() ||
    "Nuevo chat";
  const normalized = raw.replace(/\s+/g, " ");
  return normalized.length > 42 ? `${normalized.slice(0, 39).trimEnd()}...` : normalized;
}

export function loadChats(userId: string): ChatSession[] {
  if (typeof window === "undefined" || !userId) return [];

  try {
    const raw = window.localStorage.getItem(storageKey(userId));
    if (!raw) return [];
    const parsed = JSON.parse(raw) as ChatSession[];
    if (!Array.isArray(parsed)) return [];

    return parsed
      .filter(
        (chat) =>
          chat &&
          typeof chat.id === "string" &&
          typeof chat.title === "string" &&
          Array.isArray(chat.messages),
      )
      .sort((a, b) => b.updatedAt - a.updatedAt);
  } catch {
    return [];
  }
}

export function saveChats(userId: string, chats: ChatSession[]) {
  if (typeof window === "undefined" || !userId) return;

  try {
    window.localStorage.setItem(storageKey(userId), JSON.stringify(chats));
  } catch {
    /* Si el navegador alcanza su cuota, el chat actual sigue funcionando en memoria. */
  }
}
