import { api } from '@/core/services/api'
import type {
  AddressApiResponse,
  AddressPayload,
  AddressesApiResponse,
} from '../types/address.types'

export async function listAddresses(perPage = 100): Promise<AddressesApiResponse> {
  const { data } = await api.get<AddressesApiResponse>('/v1/addresses', {
    params: { per_page: perPage },
  })

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal memuatkan alamat.')
  }

  return data
}

export async function createAddress(payload: AddressPayload): Promise<AddressApiResponse> {
  const { data } = await api.post<AddressApiResponse>('/v1/addresses', payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal menambah alamat.')
  }

  return data
}

export async function updateAddress(
  id: string,
  payload: AddressPayload,
): Promise<AddressApiResponse> {
  const { data } = await api.put<AddressApiResponse>(`/v1/addresses/${id}`, payload)

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal mengemas kini alamat.')
  }

  return data
}

export async function deleteAddress(id: string): Promise<AddressApiResponse> {
  const { data } = await api.delete<AddressApiResponse>(`/v1/addresses/${id}`)

  if (!data.success) {
    throw new Error(data.message ?? 'Gagal memadam alamat.')
  }

  return data
}
