"use client";
const CONVERSATIONS_ENDPOINT = "/api/ai_assistant/ai/conversations";
function readString(value) {
  return typeof value === "string" && value.length > 0 ? value : null;
}
function buildAttachmentImagePreviewUrl(attachmentId) {
  const params = new URLSearchParams({
    width: "320",
    height: "320",
    cropType: "contain"
  });
  return `/api/attachments/image/${encodeURIComponent(attachmentId)}?${params.toString()}`;
}
function getFetch() {
  const fetchImpl = globalThis.fetch;
  return typeof fetchImpl === "function" ? fetchImpl.bind(globalThis) : null;
}
async function requestJson(input, init) {
  const fetchImpl = getFetch();
  if (!fetchImpl) return { ok: false, status: 0, data: null };
  try {
    const response = await fetchImpl(input, {
      credentials: "include",
      ...init,
      headers: {
        Accept: "application/json",
        "x-om-forbidden-redirect": "0",
        "x-om-unauthorized-redirect": "0",
        ...init?.body ? { "Content-Type": "application/json" } : {},
        ...init?.headers ?? {}
      }
    });
    if (!response.ok) return { ok: false, status: response.status, data: null };
    return { ok: true, status: response.status, data: await response.json() };
  } catch {
    return { ok: false, status: 0, data: null };
  }
}
async function listAiServerConversations(options = {}) {
  const params = new URLSearchParams();
  if (options.agentId) params.set("agent", options.agentId);
  if (options.status) params.set("status", options.status);
  params.set("limit", String(options.limit ?? 100));
  const result = await requestJson(
    `${CONVERSATIONS_ENDPOINT}?${params.toString()}`
  );
  return result.ok ? result.data.items : null;
}
async function createAiServerConversation(input) {
  const result = await requestJson(CONVERSATIONS_ENDPOINT, {
    method: "POST",
    body: JSON.stringify({
      agentId: input.agentId,
      conversationId: input.conversationId,
      title: input.title ?? void 0,
      pageContext: input.pageContext ?? void 0
    })
  });
  return result.ok ? result.data : null;
}
async function updateAiServerConversation(conversationId, patch) {
  const result = await requestJson(
    `${CONVERSATIONS_ENDPOINT}/${encodeURIComponent(conversationId)}`,
    {
      method: "PATCH",
      body: JSON.stringify(patch)
    }
  );
  return result.ok ? result.data : null;
}
async function loadAiServerTranscript(conversationId, options = {}) {
  const params = new URLSearchParams();
  params.set("limit", String(options.limit ?? 100));
  const result = await requestJson(
    `${CONVERSATIONS_ENDPOINT}/${encodeURIComponent(conversationId)}?${params.toString()}`
  );
  return result.ok ? result.data : null;
}
async function importAiLocalConversation(input) {
  const result = await requestJson(`${CONVERSATIONS_ENDPOINT}/import`, {
    method: "POST",
    body: JSON.stringify({
      conversation: {
        conversationId: input.conversationId,
        agentId: input.agentId,
        title: input.title ?? void 0,
        status: input.status ?? "open",
        pageContext: input.pageContext ?? void 0
      },
      messages: input.messages.slice(-100).map((message) => ({
        clientMessageId: message.id,
        role: message.role,
        content: message.content,
        uiParts: message.uiParts ?? [],
        files: (message.files ?? []).map((file) => ({
          id: file.id,
          name: file.name,
          mimeType: file.type
        }))
      }))
    })
  });
  return result.ok ? result.data : null;
}
function serverMessageToChatMessage(message) {
  if (message.role !== "user" && message.role !== "assistant") return null;
  const uiParts = [];
  message.uiParts.forEach((part, index) => {
    if (!part || typeof part !== "object") return;
    const value = part;
    const componentId = typeof value.componentId === "string" ? value.componentId : typeof value.type === "string" ? value.type : null;
    if (!componentId) return;
    uiParts.push({
      componentId,
      payload: value.payload ?? value.props,
      pendingActionId: typeof value.pendingActionId === "string" ? value.pendingActionId : void 0,
      key: typeof value.key === "string" ? value.key : `${message.id}:${index}:${componentId}`
    });
  });
  return {
    id: message.clientMessageId ?? message.id,
    role: message.role,
    content: message.content,
    files: message.files.map((file, index) => {
      const name = readString(file.name);
      if (!name) return null;
      const type = typeof file.mimeType === "string" ? file.mimeType : typeof file.type === "string" ? file.type : "application/octet-stream";
      const id = readString(file.id) ?? readString(message.attachmentIds[index]);
      const rawPreviewUrl = readString(file.previewUrl) ?? readString(file.thumbnailUrl) ?? readString(file.url);
      const previewUrl = type.startsWith("image/") ? rawPreviewUrl ?? (id ? buildAttachmentImagePreviewUrl(id) : void 0) : void 0;
      return {
        ...id ? { id } : {},
        name,
        type,
        ...previewUrl ? { previewUrl } : {}
      };
    }).filter((file) => file !== null),
    uiParts
  };
}
export {
  createAiServerConversation,
  importAiLocalConversation,
  listAiServerConversations,
  loadAiServerTranscript,
  serverMessageToChatMessage,
  updateAiServerConversation
};
//# sourceMappingURL=conversation-store.js.map
