import { axiosClient } from '../App.tsx';
type ContactsProps = {
  usernamecontact: string;
  read: boolean;
};

type MessagesProps = {
  sender: string;
  message: string;
  recipient: string;
  message_id: number;
  timestamp: string;
};
export async function getContactsList(): Promise<ContactsProps[]> {
  try {
    console.log('getcontactslisklsdfjklfsdjklsdfjklsdfjklsdfjklsdfjkl');
    const response = await axiosClient.get(`/api/chat/contacts`);
    console.log(response.data);
    return response.data;
  } catch (e) {
    console.error('Failed to fetch /api/chat/contacts: ', e);
    throw e;
  }
}
export async function setContactStatus(contact: string, read: boolean) {
  try {
    const response = await axiosClient.put(
      `/api/chat/contacts/${contact}`,
      { 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: MessagesProps[] }> {
  if (contact === null || cursor === null) {
    return { messages: [] };
  }
  try {
    const response = await axiosClient.get(
      `/api/chat/messages/${contact}?limit=${limit}&cursor=${cursor}`,
    );
    console.log(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);
  }
}
