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

import { newsFields } from '../constants'

const fetchFeaturedNews = async () => {
  try {
    const { data } = await http.get('content/news', {
      fields: newsFields,
      filters: {
        'status:eq': 1,
        'published_at:lte': 'now()',
        'is_featured:eq': 1,
        limit: 5,
        sort: 'published_at:desc'
      }
    })

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

const fetchEventSpaces = async ({ $route }) => {
  try {
    const { data } = await http.get('content/spaces', {
      fields: ['uuid', 'title', 'slug', 'admin', 'content_type', 'visibility'],
      filters: { 'slug:eq': $route.params.slug }
    })

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

const fetchSupplies = async ({ $route }) => {
  try {
    const { data } = await http.get('content/supplies_categories', {
      fields: [
        'uuid',
        'title',
        'content_type',
        'admin',
        {
          supplies: {
            fields: ['title', 'uuid', 'admin', 'content_type'],
            filters: { reverse: true, 'status:eq': 1, sort: 'title:asc' }
          }
        }
      ],
      filters: { 'status:eq': 1, sort: 'title:asc' }
    })

    const { data: custom } = await http.get('content/custom', {
      fields: [
        'uuid',
        'title',
        'introduction',
        'banner',
        'admin',
        'content_type'
      ],
      filters: { 'custom_slug:eq': $route.meta.customSlug }
    })

    return { ...custom[0], supplies_categories: data }
  } catch (err) {
    throw new Error(err)
  }
}

export { fetchFeaturedNews, fetchEventSpaces, fetchSupplies }
