import apiClient from '../../../shared/services/apiClient';

export interface Chat {
  id: number;
  visitor_id?: number;
  visitor_name?: string;
  visitor_email?: string;
  staff_id?: number;
  staff_name?: string;
  status: 'pending' | 'active' | 'closed';
  created_at: string;
  updated_at: string;
  message_count?: number;
}

export interface ChatMessage {
  id: number;
  chat_id: number;
  sender_id?: number;
  sender_type: 'visitor' | 'staff';
  sender_name?: string;
  message: string;
  is_read: boolean;
  created_at: string;
}

export interface CreateChatRequest {
  visitor_name?: string;
  visitor_email?: string;
  visitor_phone?: string;
}

export interface CreateChatResponse {
  success: boolean;
  data: Chat;
}

export interface ChatListResponse {
  success: boolean;
  data: Chat[];
}

export interface ChatMessagesResponse {
  success: boolean;
  data: ChatMessage[];
}

export interface SendMessageRequest {
  message: string;
}

export interface SendMessageResponse {
  success: boolean;
  data: ChatMessage;
}

export const createChat = async (
  data?: CreateChatRequest
): Promise<CreateChatResponse> => {
  const response = await apiClient.post('/chat/create', null, {
    params: data
  });
  return response.data;
};

export const acceptChat = async (
  chatId: number
): Promise<{ success: boolean; data: Chat }> => {
  const response = await apiClient.post(`/chat/${chatId}/accept`);
  return response.data;
};

export const listChats = async (
  statusFilter?: string
): Promise<ChatListResponse> => {
  const response = await apiClient.get('/chat/list', {
    params: statusFilter ? { status_filter: statusFilter } : {}
  });
  return response.data;
};

export const getChat = async (
  chatId: number
): Promise<{ success: boolean; data: Chat }> => {
  const response = await apiClient.get(`/chat/${chatId}`);
  return response.data;
};

export const getMessages = async (
  chatId: number
): Promise<ChatMessagesResponse> => {
  const response = await apiClient.get(`/chat/${chatId}/messages`);
  return response.data;
};

export const sendMessage = async (
  chatId: number,
  message: string
): Promise<SendMessageResponse> => {
  const response = await apiClient.post(`/chat/${chatId}/message`, null, {
    params: { message }
  });
  return response.data;
};

export const closeChat = async (
  chatId: number
): Promise<{ success: boolean; data: Chat }> => {
  const response = await apiClient.post(`/chat/${chatId}/close`);
  return response.data;
};

export default {
  createChat,
  acceptChat,
  listChats,
  getChat,
  getMessages,
  sendMessage,
  closeChat,
};

