/**
 * 会话与历史消息（Client Chat）。
 *
 * 类型与 `http://localhost:3000/docs` 中 components schemas 对齐：
 * `CreateChatSessionDto`、`ChatSessionRowDto`、`ChatSessionListResponseDto`、
 * `ChatMessageRowDto`、`ChatMessageListResponseDto`。
 */
import { deleteJson, getJson, patchJson, postJson } from "./http";
import { ApiPath, chatSessionMessagesPath, chatSessionPath, chatSessionTitlePath } from "./paths";

/** `CreateChatSessionDto` */
export type CreateChatSessionBody = {
  /** 会话标题，可选，最长 200 */
  title?: string;
};

/** `ChatSessionRowDto` */
export type ChatSessionRowDto = {
  id: string;
  userId: string;
  title: string;
  createdAt: string;
  updatedAt: string;
};

/** 侧栏与会话列表中的「一条会话」 */
export type ChatSession = ChatSessionRowDto;

/** `ChatSessionListResponseDto` */
export type ChatSessionListResponseDto = {
  items: ChatSessionRowDto[];
  total: number;
  limit: number;
  offset: number;
};

/** `ChatMessageRowDto` */
export type ChatMessageRowDto = {
  id: string;
  role: string;
  content: string;
  tokenCount: number;
  provider?: string | null;
  createdAt: string;
};

/** `ChatMessageListResponseDto` */
export type ChatMessageListResponseDto = {
  sessionId: string;
  items: ChatMessageRowDto[];
  total: number;
  limit: number;
  offset: number;
};

export type ListSessionsQuery = {
  offset?: number;
  limit?: number;
};

export type ListMessagesQuery = {
  offset?: number;
  limit?: number;
};

/** `UpdateChatSessionTitleDto` */
export type UpdateChatSessionTitleBody = {
  /** 会话标题（可传空字符串清空） */
  title: string;
};

/** 与首页消息列表结构一致，便于 `setMessages` */
export type ChatTurnForUi = {
  id: string;
  role: "user" | "assistant";
  content: string;
  thinking?: string;
};

export function sessionStableId(s: ChatSessionRowDto): string {
  return s.id;
}

/** 侧栏展示标题（`title` 可能为空字符串） */
export function sessionDisplayTitle(s: ChatSessionRowDto): string {
  const t = s.title.trim();
  if (t) return t;
  return `会话 ${s.id.slice(0, 8)}…`;
}

/**
 * 创建会话（可选标题）。
 * 响应为 `ChatSessionRowDto`（OpenAPI 标注为 200）。
 */
export async function createChatSession(
  body: CreateChatSessionBody = {},
  signal?: AbortSignal,
): Promise<ChatSessionRowDto> {
  return postJson<ChatSessionRowDto>(ApiPath.chatSessions, body, signal);
}

/** 分页拉取会话列表 */
export async function listChatSessions(
  query?: ListSessionsQuery,
  signal?: AbortSignal,
): Promise<ChatSessionRowDto[]> {
  const data = await getJson<ChatSessionListResponseDto>(ApiPath.chatSessions, query, signal);
  return data.items;
}

/** 分页拉取某会话下的消息 */
export async function listChatSessionMessages(
  sessionId: string,
  query?: ListMessagesQuery,
  signal?: AbortSignal,
): Promise<ChatMessageRowDto[]> {
  const path = chatSessionMessagesPath(sessionId);
  const data = await getJson<ChatMessageListResponseDto>(path, query, signal);
  return data.items;
}

/** 修改会话标题 */
export async function updateChatSessionTitle(
  sessionId: string,
  body: UpdateChatSessionTitleBody,
  signal?: AbortSignal,
): Promise<ChatSessionRowDto> {
  const path = chatSessionTitlePath(sessionId);
  return patchJson<ChatSessionRowDto>(path, body, signal);
}

/** 删除会话（级联删除消息） */
export async function deleteChatSession(sessionId: string, signal?: AbortSignal): Promise<void> {
  const path = chatSessionPath(sessionId);
  await deleteJson<void>(path, signal);
}

/** 将接口消息行规范为前端聊天列表项（忽略 `system` 等角色） */
export function normalizeSessionMessages(rows: ChatMessageRowDto[]): ChatTurnForUi[] {
  const out: ChatTurnForUi[] = [];
  for (const row of rows) {
    if (row.role !== "user" && row.role !== "assistant") continue;
    out.push({
      id: row.id,
      role: row.role,
      content: row.content,
    });
  }
  return out;
}
