import { request, headers, BASE } from "./client";

export const listChats = (token) => request("GET", "/chats", token);

export const createChat = (token, data = {}) =>
  request("POST", "/chats", token, data);

export const updateChat = (token, chatId, data) =>
  request("PUT", `/chats/${chatId}`, token, data);

export const renameChat = (token, chatId, title) =>
  updateChat(token, chatId, { title });

export const deleteChat = (token, chatId) =>
  request("DELETE", `/chats/${chatId}`, token);

export const getMessages = (token, chatId) =>
  request("GET", `/chats/${chatId}/messages`, token);

export const checkGenerating = (token, chatId) =>
  request("GET", `/chats/${chatId}/generating`, token);

export async function* streamMessage(token, chatId, body, signal) {
  const res = await fetch(`${BASE}/chats/${chatId}/messages`, {
    method: "POST", headers: headers(token),
    body: JSON.stringify(body), signal,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(err.detail || "Stream failed");
  }
  const reader = res.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    buffer += decoder.decode(value, { stream: true });
    const parts = buffer.split("\n\n");
    buffer = parts.pop() || "";
    for (const part of parts) {
      const line = part.trim();
      if (line.startsWith("data: ")) {
        try { yield JSON.parse(line.slice(6)); } catch { }
      }
    }
  }
  if (buffer.trim().startsWith("data: ")) {
    try { yield JSON.parse(buffer.trim().slice(6)); } catch { }
  }
}

// User-facing GitLab integration (routes under /chats/)
export const listLinkedRepos = (token) =>
  request("GET", "/chats/available-repos", token);

export const getRepoBranches = (token, repoId) =>
  request("GET", `/chats/repos/${repoId}/branches`, token);

export const commitFromChat = (token, chatId, data) =>
  request("POST", `/chats/${chatId}/commit`, token, data);

export const refreshRepoContext = (token, chatId) =>
  request("POST", `/chats/${chatId}/refresh-repo`, token);
