import { ChatMessagesProps, ContactsProps } from '@/types/types.ts';
import { axiosClient } from '@/utils/axiosClient.ts';

export async function getContactsList(): Promise<ContactsProps[]> {
  try {
    const response = await axiosClient.get(`/api/chat/contacts`);
    console.log('Get contacts list response: ', response.data);
    return response.data;
  } catch (e) {
    console.error('Failed to fetch /api/chat/contacts: ', e);
    throw e;
  }
}

export async function setContactStatus(conversation_id: string, read: boolean) {
  try {
    const response = await axiosClient.put(
      `/api/chat/contacts/${conversation_id}`,
      { status: read },
      { withCredentials: true },
    );
    console.log(response.data);
    return response.data;
  } catch (e) {
    console.error('Failed to set contact status: ', e);
    throw e;
  }
}

export async function sendContact(contact: string) {
  try {
    const response = await axiosClient.post(`/api/chat/contact/${contact}`);
    console.log(response.data);
    return response.data;
  } catch (e) {
    console.error('Failed to send contact: ', e);
    throw e;
  }
}

export async function getMessages(
  contact: string | null,
  cursor: number | null = 0,
  limit: number = 50,
): Promise<{ messages: ChatMessagesProps[] }> {
  if (contact === null || cursor === null) {
    return { messages: [] };
  }
  try {
    const response = await axiosClient.get(
      `/api/chat/messages/${contact}?limit=${limit}&cursor=${cursor}`,
    );
    console.log('Get messages response: ', response.data);

    return response.data;
  } catch (e) {
    console.error('Failed to get messages: ', e);
    throw e;
  }
}

export async function deleteContact(usernamecontact: string) {
  try {
    const response = await axiosClient.delete(
      `/api/chat/contacts/${usernamecontact}`,
    );
    console.log(response.data);
    return response.data;
  } catch (e) {
    console.error('Failed to delete contact: ', e);
  }
}
