import { apiFetch } from './auth';

export interface Friend {
  id: string;
  username: string;
  status: 'accepted' | 'pending';
  requestId?: string;
}

export interface FriendRequest {
  id: string;
  username: string;
  requestId: string;
  status: 'pending';
}

export interface FriendsResponse {
  friends: Friend[];
  incoming: FriendRequest[];
  outgoing: FriendRequest[];
}

export async function getFriends(): Promise<FriendsResponse> {
  const response = await apiFetch('/friends');
  return response.json();
}

export async function searchUsers(query: string): Promise<Friend[]> {
  const response = await apiFetch(`/friends/search?q=${encodeURIComponent(query)}`);
  return response.json();
}

export async function sendFriendRequest(username: string): Promise<void> {
  const response = await apiFetch('/friends/requests', {
    method: 'POST',
    body: JSON.stringify({ username }),
  });
  if (!response.ok) {
    const data = await response.json();
    throw new Error(data.message || 'Failed to send friend request');
  }
}

export async function acceptFriendRequest(requestId: string): Promise<void> {
  const response = await apiFetch(`/friends/requests/${requestId}/accept`, {
    method: 'POST',
  });
  if (!response.ok) {
    const data = await response.json();
    throw new Error(data.message || 'Failed to accept friend request');
  }
}

export async function deleteFriendRequest(requestId: string): Promise<void> {
  const response = await apiFetch(`/friends/requests/${requestId}`, {
    method: 'DELETE',
  });
  if (!response.ok) {
    const data = await response.json();
    throw new Error(data.message || 'Failed to decline friend request');
  }
}

export async function removeFriend(friendId: string): Promise<void> {
  const response = await apiFetch(`/friends/${friendId}`, {
    method: 'DELETE',
  });
  if (!response.ok) {
    const data = await response.json();
    throw new Error(data.message || 'Failed to remove friend');
  }
}