import axios from 'src/utils/axios';

// ----------------------------------------------------------------------

export async function getConversations(params) {
  const res = await axios.get('/chat/chats/', { params });
  const {data} = res;
  if (Array.isArray(data)) return { count: data.length, next: null, previous: null, results: data };
  return {
    count: data?.count ?? (data?.results?.length ?? 0),
    next: data?.next ?? null,
    previous: data?.previous ?? null,
    results: data?.results ?? [],
  };
}

export async function getChatById(uuid) {
  const res = await axios.get(`/chat/chats/${uuid}/`);
  return res.data;
}

export async function createChat(participantId) {
  const res = await axios.post('/chat/chats/', { participants: [participantId] });
  return res.data;
}

export async function getChatMessagesByUuid(chatUuid, params) {
  const res = await axios.get(`/chat/chats/${chatUuid}/messages/`, { params });
  return res.data;
}

export async function getMessages(chatId, params) {
  const res = await axios.get('/chat/messages/', { params: { ...params, chat: chatId } });
  return res.data;
}

export async function sendMessage(chatId, content, file) {
  const formData = new FormData();
  formData.append('chat', String(chatId));
  formData.append('content', content);
  if (file) formData.append('file', file);
  const res = await axios.post('/chat/messages/', formData);
  const {data} = res;
  if (data && typeof data === 'object' && 'data' in data) return data.data;
  return data;
}

export async function markMessagesAsRead(chatUuid, messageUuids) {
  await axios.post(
    `/chat/chats/${chatUuid}/mark_read/`,
    messageUuids ? { message_uuids: messageUuids } : {}
  );
}

export async function searchUsers(query) {
  const res = await axios.get('/users/search/', { params: { q: query } });
  const {data} = res;
  if (Array.isArray(data)) return data;
  return data?.results ?? [];
}
