import type { ShippingAddress } from '@/entities/user/model/types'
import { apiClient } from '@/shared/api/client'

export type AddressesListResponse = { items: ShippingAddress[] }

export async function fetchMyAddresses(): Promise<AddressesListResponse> {
  const { data } = await apiClient.get<AddressesListResponse>('me/addresses')
  return data
}

export async function createMyAddress(body: {
  label?: string | null
  recipientName: string
  recipientPhone: string
  addressLine: string
  comment?: string | null
  lat: number
  lng: number
  isDefault?: boolean
}): Promise<{ item: ShippingAddress }> {
  const { data } = await apiClient.post<{ item: ShippingAddress }>('me/addresses', body)
  return data
}

export async function updateMyAddress(
  id: string,
  body: Partial<{
    label: string | null
    recipientName: string
    recipientPhone: string
    addressLine: string
    comment: string | null
    lat: number
    lng: number
    isDefault: boolean
  }>,
): Promise<{ item: ShippingAddress }> {
  const { data } = await apiClient.patch<{ item: ShippingAddress }>(`me/addresses/${id}`, body)
  return data
}

export async function deleteMyAddress(id: string): Promise<void> {
  await apiClient.delete(`me/addresses/${id}`)
}

export async function setMyAddressDefault(id: string): Promise<{ item: ShippingAddress }> {
  const { data } = await apiClient.post<{ item: ShippingAddress }>(`me/addresses/${id}/default`)
  return data
}
