import { apiRequest } from '../lib/api'
import type { CityOption } from '@meshkee/dashboard-ui'

export type { CityOption }

export async function listCountries(signal?: AbortSignal) {
  const data = await apiRequest<{ items: CityOption[] }>('/cities?level=country', { signal })
  return data.items
}

/** Cities under a country (direct + via provinces). Province is optional in the tree. */
export async function listCitiesByCountrySlug(parentSlug: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: CityOption[] }>(
    `/cities?level=city&parentSlug=${encodeURIComponent(parentSlug)}`,
    { signal },
  )
  return data.items
}

export async function listProvincesByCountrySlug(parentSlug: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: CityOption[] }>(
    `/cities?level=province&parentSlug=${encodeURIComponent(parentSlug)}`,
    { signal },
  )
  return data.items
}

/** @deprecated Prefer listProvincesByCountrySlug('iran') */
export async function listIranProvinces(signal?: AbortSignal) {
  return listProvincesByCountrySlug('iran', signal)
}

export async function listCitiesByProvinceSlug(parentSlug: string, signal?: AbortSignal) {
  const data = await apiRequest<{ items: CityOption[] }>(
    `/cities?level=city&parentSlug=${encodeURIComponent(parentSlug)}`,
    { signal },
  )
  return data.items
}
