import { API_BASE_URL } from "@/lib/config";

const BASE_URL = API_BASE_URL;

// --- Types ---

export type SessionMessage = {
  role: "user" | "assistant" | "tool";
  content: string | Array<{ type: string; [key: string]: unknown }>;
  name?: string;
  tool_call_id?: string;
  timestamp?: string;
  thinking_steps?: Array<{
    type: "thinking" | "tool_call" | "tool_result" | "error";
    content?: string;
    name?: string;
    result?: string;
    success?: boolean;
  }>;
  display_text?: string;
  attached_files?: Array<{ name: string; size: number; isImage: boolean }>;
};

export type SessionInfo = {
  id: string;
  title: string;
  created_at: string;
  updated_at: string;
  message_count: number;
  preview: string;
};

export type SessionDetail = {
  info: SessionInfo;
  messages: SessionMessage[];
};

// --- API ---

export async function fetchSessions(): Promise<SessionInfo[]> {
  const res = await fetch(`${BASE_URL}/api/sessions/`);
  if (!res.ok) throw new Error("Failed to fetch sessions");
  return res.json();
}

export async function createSession(title: string = ""): Promise<SessionInfo> {
  const res = await fetch(`${BASE_URL}/api/sessions/`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  if (!res.ok) throw new Error("Failed to create session");
  return res.json();
}

export async function fetchSession(id: string): Promise<SessionDetail> {
  const res = await fetch(`${BASE_URL}/api/sessions/${id}`);
  if (!res.ok) throw new Error("Failed to fetch session");
  return res.json();
}

export async function saveMessages(id: string, messages: SessionMessage[]): Promise<SessionInfo> {
  const res = await fetch(`${BASE_URL}/api/sessions/${id}/messages`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ messages }),
  });
  if (!res.ok) throw new Error("Failed to save messages");
  return res.json();
}

export async function updateSession(id: string, title: string): Promise<SessionInfo> {
  const res = await fetch(`${BASE_URL}/api/sessions/${id}`, {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ title }),
  });
  if (!res.ok) throw new Error("Failed to update session");
  return res.json();
}

export async function deleteSession(id: string): Promise<void> {
  const res = await fetch(`${BASE_URL}/api/sessions/${id}`, {
    method: "DELETE",
  });
  if (!res.ok) throw new Error("Failed to delete session");
}
