import client from './client'
import type { User, UserProfilePublic, UserStats, PasswordChangeData, NotificationSettings, NotificationSettingsUpdate } from '@/types'

export interface UpdateNicknameData {
  nickname: string
}

export const usersApi = {
  // Получить публичный профиль пользователя со статистикой
  getProfile: async (userId: number): Promise<UserProfilePublic> => {
    const response = await client.get<UserProfilePublic>(`/users/${userId}/profile`)
    return response.data
  },

  // Получить свою статистику
  getMyStats: async (): Promise<UserStats> => {
    const response = await client.get<UserStats>('/users/me/stats')
    return response.data
  },

  // Обновить никнейм
  updateNickname: async (data: UpdateNicknameData): Promise<User> => {
    const response = await client.patch<User>('/users/me', data)
    return response.data
  },

  // Загрузить аватар
  uploadAvatar: async (file: File): Promise<User> => {
    const formData = new FormData()
    formData.append('file', file)
    const response = await client.post<User>('/users/me/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    })
    return response.data
  },

  // Сменить пароль
  changePassword: async (data: PasswordChangeData): Promise<{ message: string }> => {
    const response = await client.post<{ message: string }>('/users/me/password', data)
    return response.data
  },

  // Получить аватар пользователя как blob URL
  getAvatarUrl: async (userId: number, bustCache = false): Promise<string> => {
    const cacheBuster = bustCache ? `?t=${Date.now()}` : ''
    const response = await client.get(`/users/${userId}/avatar${cacheBuster}`, {
      responseType: 'blob',
    })
    return URL.createObjectURL(response.data)
  },

  // Получить настройки уведомлений
  getNotificationSettings: async (): Promise<NotificationSettings> => {
    const response = await client.get<NotificationSettings>('/users/me/notifications')
    return response.data
  },

  // Обновить настройки уведомлений
  updateNotificationSettings: async (data: NotificationSettingsUpdate): Promise<NotificationSettings> => {
    const response = await client.patch<NotificationSettings>('/users/me/notifications', data)
    return response.data
  },
}
