import { http } from '@inside-library/helpers/Http'

import { basicFields, newsFields } from '../constants'

const fetchSpace = async ({ $route }) => {
  try {
    const { data } = await http.get('content/spaces', {
      fields: [
        ...basicFields,
        'image',
        'chapo',
        {
          users: [
            'image',
            'firstname',
            'lastname',
            'function',
            'mobile_phone',
            'uuid'
          ]
        }
      ],
      filters: { 'slug:eq': $route.params.slug }
    })

    return data[0]
  } catch (err) {
    throw new Error(err)
  }
}

const fetchSpacePage = async ({ $route }) => {
  try {
    const { data } = await http.get('content/spaces_pages', {
      fields: [
        ...basicFields,
        'content',
        'image',
        {
          spaces_pages_categories: [{ spaces: ['uuid', 'title', 'slug'] }]
        }
      ],
      filters: { 'slug:eq': $route.params.slug }
    })

    return data[0]
  } catch (err) {
    throw new Error(err)
  }
}

const fetchHrNews = async ({ $route }) => {
  try {
    const { data } = await http.get('content/news', {
      fields: newsFields,
      filters: {
        'status:eq': 1,
        sort: 'published_at:desc',
        'published_at:lte': 'now()',
        limit: 4,
        news_categories: {
          'slug:eq': 'ressources-humaines'
        }
      }
    })

    return data
  } catch (err) {
    throw new Error(err)
  }
}

export { fetchSpace, fetchSpacePage, fetchHrNews }
