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

export const fetchSpacePage = async ({ $route }) => {
  try {
    const { data } = await http.get('content/spaces', {
      fields: [
        'uuid',
        'admin',
        'title',
        'slug',
        'content_type',
        'introduction',
        'banner',
        'admin',
        'display_new_users',
        {
          users: {
            fields: [
              'uuid',
              'firstname',
              'lastname',
              'image',
              'function',
              'phone',
              'mobile_phone'
            ],
            filters: {
              'status:eq': 1
            }
          }
        },
        {
          tools: {
            fields: [
              'title',
              'uuid',
              'has_section',
              'tools_link',
              'admin',
              'image',
              'class',
              'content_type',
              'icon',
              {
                tools_categories: [
                  'uuid',
                  { tools_categories_listings: ['uuid', 'slug'] }
                ]
              }
            ],
            filters: {
              'status:eq': 1
            }
          }
        },
        {
          news_categories: {
            fields: [
              'uuid',
              'title',
              {
                news: {
                  fields: [
                    'uuid',
                    'title',
                    'slug',
                    'introduction',
                    'published_at',
                    'image',
                    'chapo',
                    'content_type',
                    { news_categories: ['uuid', 'title'] },
                    { subsidiaries: ['uuid', 'title'] },
                    { reactions: ['count', { users: ['uuid'] }] },
                    { comments: ['count'] }
                  ],
                  filters: {
                    reverse: true,
                    'status:eq': 1,
                    sort: 'published_at:desc',
                    'published_at:lte': 'now()',
                    limit: 4
                  }
                }
              }
            ],
            filters: {
              'status:eq': 1,
              'published_at:lte': 'now()'
            }
          }
        },
        {
          pages_categories: { fields: ['count'], filters: { reverse: true } }
        }
      ],
      filters: { 'slug:eq': $route.params.slug }
    })

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

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

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