import { api } from '@/core/services/api'
import type {
  EmploymentApiResponse,
  EmploymentPayload,
  EmploymentsApiResponse,
} from '../types/employment.types'

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

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

  return data
}

export async function createEmployment(payload: EmploymentPayload): Promise<EmploymentApiResponse> {
  const { data } = await api.post<EmploymentApiResponse>('/v1/employments', payload)

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

  return data
}

export async function updateEmployment(
  id: string,
  payload: EmploymentPayload,
): Promise<EmploymentApiResponse> {
  const { data } = await api.put<EmploymentApiResponse>(`/v1/employments/${id}`, payload)

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

  return data
}

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

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

  return data
}
