import client from '../client';

/* ── Types ── */

export interface ChatSession {
  id: string;
  title: string;
  agent_type: string;
  created_at: string;
  updated_at: string;
  message_count?: number;
}

export interface ChatMessage {
  id: string;
  session_id?: string;
  role: 'user' | 'assistant';
  content: string;
  model_id?: string;
  status?: 'processing' | 'done' | 'failed';
  created_at?: string;
}

export interface ChatSendBody {
  message: string;
  session_id?: string;
  genai_config_id?: string;
  model_id?: string;
  oci_config_id?: string;
  genai_region?: string;
  compartment_id?: string;
  temperature?: number;
  max_tokens?: number;
  top_p?: number;
  top_k?: number;
  frequency_penalty?: number;
  presence_penalty?: number;
  reasoning_effort?: string;
  use_tools?: boolean;
}

export interface ChatSendResponse {
  message_id: string;
  session_id: string;
  status: 'processing' | 'done';
}

export interface MessageStatusResponse {
  id: string;
  session_id: string;
  role: string;
  content: string;
  model_id?: string;
  status: 'processing' | 'done' | 'failed';
}

export interface SessionMessagesResponse {
  session: ChatSession;
  messages: ChatMessage[];
}

/* ── API ── */

export const chatApi = {
  /** Send a chat message (text only) */
  send: (body: ChatSendBody) =>
    client.post('/chat', body) as unknown as Promise<ChatSendResponse>,

  /** Send a chat message with file attachments */
  upload: (formData: FormData) =>
    client.post('/chat/upload', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }) as unknown as Promise<ChatSendResponse>,

  /** Poll message processing status */
  pollStatus: (messageId: string) =>
    client.get(`/chat/${messageId}/status`) as unknown as Promise<MessageStatusResponse>,

  /** List chat sessions */
  listSessions: (agentType = 'chat', limit = 50) =>
    client.get(`/chat/sessions?agent_type=${agentType}&limit=${limit}`) as unknown as Promise<ChatSession[]>,

  /** Load session with all messages */
  loadSession: (sessionId: string) =>
    client.get(`/chat/sessions/${sessionId}/messages`) as unknown as Promise<SessionMessagesResponse>,

  /** Delete a session */
  deleteSession: (sessionId: string) =>
    client.delete(`/chat/${sessionId}`) as unknown as Promise<{ ok: boolean }>,

  /** Rename a session */
  renameSession: (sessionId: string, title: string) =>
    client.put(`/chat/sessions/${sessionId}/title`, { title }) as unknown as Promise<{ ok: boolean }>,
};
