import type { Site } from './dto/site'
import { extractItems } from '~/utils/api'

export const listSites = async () => {
  const api = useApi()
  const data = await api.get<Site[] | { 'hydra:member'?: Site[] }>(
    '/sites',
    {},
    { toast: false }
  )
  return extractItems<Site>(data).sort((siteA, siteB) => {
    const orderA = siteA.displayOrder ?? 0
    const orderB = siteB.displayOrder ?? 0
    if (orderA !== orderB) return orderA - orderB
    return siteA.name.localeCompare(siteB.name, 'fr')
  })
}

export const createSite = async (payload: Pick<Site, 'name' | 'color'> & { displayOrder?: number }) => {
  const api = useApi()
  return api.post<Site>('/sites', payload, {
    toastSuccessKey: 'success.site.create',
    toastErrorKey: 'errors.site.create'
  })
}

export const updateSite = async (
  id: number,
  payload: Pick<Site, 'name' | 'color'> & { displayOrder?: number }
) => {
  const api = useApi()
  return api.patch<Site>(`/sites/${id}`, payload, {
    toastSuccessKey: 'success.site.update',
    toastErrorKey: 'errors.site.update'
  })
}

export const updateSiteOrder = async (id: number, displayOrder: number) => {
  const api = useApi()
  return api.patch<Site>(`/sites/${id}`, {
    displayOrder
  }, {
    toast: false
  })
}

export const deleteSite = async (id: number) => {
  const api = useApi()
  return api.delete(`/sites/${id}`, {}, {
    toastSuccessKey: 'success.site.delete',
    toastErrorKey: 'errors.site.delete'
  })
}
