import { apiFetch, assertNoErrorMessage } from './api-client'

export interface Station {
  id: number
  name: string
  address: string
  cityId: number
  companyId?: number | null
  createdAt: string
  updatedAt: string
}

export interface StationsMeta {
  total: number
  perPage: number
  page: number
  lastPage: number
}

export interface PaginatedStations {
  data: Station[]
  meta: StationsMeta
}

export const getStations = async ({
  page = 1,
  perPage = 25,
  q = '',
}: {
  page?: number
  perPage?: number
  q?: string
} = {}): Promise<PaginatedStations> => {
  return apiFetch('/stations', { params: { page, perPage, q } })
}

export const createStation = async (station: {
  name: string
  address: string
  cityId: number
  companyId?: number
}): Promise<Station> => {
  const result = await apiFetch<{ data: Station; message?: string }>('/stations', {
    method: 'POST',
    body: station,
  })
  assertNoErrorMessage(result)
  return result.data
}

export const updateStation = async (
  id: number,
  station: { name?: string; address?: string; cityId?: number; companyId?: number }
): Promise<Station> => {
  const result = await apiFetch<{ data: Station; message?: string }>(`/stations/${id}`, {
    method: 'PUT',
    body: station,
  })
  assertNoErrorMessage(result)
  return result.data
}

export const deleteStation = async (id: number): Promise<void> => {
  await apiFetch(`/stations/${id}`, { method: 'DELETE' })
}
