import { serverRequest } from "./serverConnection";

export interface ConversationSummary {
  id: number;
  title: string;
  mode: string;
  createdAt: string;
  updatedAt: string;
}

export interface ConversationDetail extends ConversationSummary {
  messages: ConversationMessage[];
}

export interface ConversationMessage {
  id: string;
  role: "user" | "assistant";
  author: string;
  mode: string;
  body: string;
  createdAt: string;
  status?: string;
  taskId?: string;
  conversationId?: number;
  taskProgress?: number;
  taskStatusLabel?: string;
  attachments?: Array<{ kind: string; name: string; token: string; previewUrl?: string; remoteUrl?: string }>;
  resultUrl?: string;
  resultType?: string;
  resultOriginalUrl?: string;
  resultOssKey?: string;
  resultMimeType?: string;
  result?: { title: string; summary: string; specs: string[] };
}

export interface DeleteConversationOptions {
  cleanupUserData?: boolean;
}

export const conversationClient = {
  async list(): Promise<ConversationSummary[]> {
    const data = await serverRequest<{ conversations: ConversationSummary[] }>("conversations");
    return data.conversations || [];
  },

  async create(title: string, mode: string, messages?: ConversationMessage[]): Promise<ConversationSummary> {
    const data = await serverRequest<{ conversation: ConversationSummary }>("conversations", {
      method: "POST",
      body: { title, mode, messages },
    });
    return data.conversation;
  },

  async get(id: number): Promise<ConversationDetail> {
    const data = await serverRequest<{ conversation: ConversationDetail }>(`conversations/${id}`);
    return data.conversation;
  },

  async update(id: number, data: { title?: string; messages?: ConversationMessage[] }): Promise<void> {
    await serverRequest(`conversations/${id}`, { method: "PUT", body: data });
  },

  async delete(id: number, options?: DeleteConversationOptions): Promise<void> {
    const path = options?.cleanupUserData ? `conversations/${id}?cleanupUserData=1` : `conversations/${id}`;
    await serverRequest(path, { method: "DELETE" });
  },
};
