import axios from 'src/utils/axios';

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

export async function getProfileSettings() {
  const res = await axios.get('/profile/settings/');
  return res.data;
}

export async function updateProfileSettings(data) {
  await axios.patch('/profile/update_settings/', data);
}

export async function searchCities(query, limit = 50) {
  try {
    const params = new URLSearchParams({ q: query, limit: String(limit) });
    const res = await axios.get(`/profile/cities/search/?${params.toString()}`);
    return Array.isArray(res.data) ? res.data : [];
  } catch {
    return [];
  }
}

export async function updateProfile(data) {
  const hasFile = data.avatar instanceof File;
  if (hasFile) {
    const formData = new FormData();
    if (data.first_name !== undefined) formData.append('first_name', data.first_name);
    if (data.last_name !== undefined) formData.append('last_name', data.last_name);
    if (data.phone !== undefined) formData.append('phone', data.phone);
    if (data.bio !== undefined) formData.append('bio', data.bio);
    formData.append('avatar', data.avatar);
    const res = await axios.patch('/profile/me/', formData);
    return res.data;
  }
  const res = await axios.patch('/profile/me/', data);
  return res.data;
}

export async function deleteAvatar() {
  const res = await axios.patch('/profile/update_profile/', { avatar: null });
  return res.data;
}

export async function loadTelegramAvatar() {
  const res = await axios.post('/profile/load_telegram_avatar/');
  const {data} = res;
  return data?.user ?? data;
}

export async function getNotificationPreferences() {
  try {
    const res = await axios.get('/notifications/preferences/me/');
    return res.data?.data ?? res.data;
  } catch {
    return null;
  }
}

export async function updateNotificationPreferences(preferences) {
  const res = await axios.patch('/notifications/preferences/me/', preferences);
  return res.data?.data ?? res.data;
}
