import { api } from '@/core/services/api'
import type { HeirApiResponse, HeirPayload, HeirsApiResponse } from '../types/heir.types'

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

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

  return data
}

export async function createHeir(payload: HeirPayload): Promise<HeirApiResponse> {
  const { data } = await api.post<HeirApiResponse>('/v1/heirs', payload)

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

  return data
}

export async function updateHeir(id: string, payload: HeirPayload): Promise<HeirApiResponse> {
  const { data } = await api.put<HeirApiResponse>(`/v1/heirs/${id}`, payload)

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

  return data
}

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

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

  return data
}
