import client from '../client';

export interface ChatHistoryItem {
  role: 'user' | 'assistant';
  content: string;
}

export type DisplayHint =
  | {
      type: 'vital_card';
      indicator_type: string;
      values: [string, number][];
      unit: string;
    }
  | {
      type: 'lab_report_card';
      report_date: string;
      abnormal_count: number;
    }
  | {
      type: 'action_confirm';
      action_type: string;
      summary: string;
      confirm_payload: unknown;
    }
  | {
      type: 'risk_alert';
      level: string;
      message: string;
    }
  | {
      type: 'trend_chart';
      metrics: string[];
      period: string;
      summary: string;
    }
  | {
      type: 'insight_card';
      title: string;
      severity: string;
      items: string[];
    }
  | {
      type: 'patient_profile';
      chronic_conditions: string[];
      medication_count: number;
    }
  | { type: 'text' };

export interface ChatResponse {
  reply: string;
  message_id: string;
  iterations: number;
  display_hints?: DisplayHint[];
}

export interface ChatSession {
  id: string;
  title: string | null;
  patient_id: string | null;
  status: string;
  created_at: string;
  updated_at: string;
}

export const aiChatApi = {
  sendMessage: async (
    message: string,
    history: ChatHistoryItem[],
    patientId?: string,
    sessionId?: string
  ): Promise<ChatResponse> => {
    const resp = await client.post('/ai/chat', {
      message,
      history,
      ...(patientId ? { patient_id: patientId } : {}),
      ...(sessionId ? { session_id: sessionId } : {}),
    });
    return resp.data.data as ChatResponse;
  },

  createSession: async (
    patientId?: string,
    title?: string
  ): Promise<ChatSession> => {
    const resp = await client.post('/ai/chat/sessions', {
      ...(patientId ? { patient_id: patientId } : {}),
      ...(title ? { title } : {}),
    });
    return resp.data.data as ChatSession;
  },

  listSessions: async (): Promise<ChatSession[]> => {
    const resp = await client.get('/ai/chat/sessions');
    return resp.data.data as ChatSession[];
  },

  renameSession: async (
    sessionId: string,
    title: string
  ): Promise<void> => {
    await client.put(`/ai/chat/sessions/${sessionId}/rename`, { title });
  },

  closeSession: async (sessionId: string): Promise<void> => {
    await client.post(`/ai/chat/sessions/${sessionId}/close`);
  },

  getSessionMessages: async (sessionId: string): Promise<Array<{
    id: string;
    role: string;
    content: string | null;
    created_at: string;
  }>> => {
    const resp = await client.get(`/ai/chat/sessions/${sessionId}/messages`);
    return resp.data.data;
  },
};
