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

const fetchFlashInfos = async () => {
  try {
    const { data } = await http.get('content/infos_flash', {
      fields: ['uuid', 'title', 'content', 'users_status'],
      filters: {
        limit: 2,
        'status:eq': 1,
        'published_at:lte': 'now()',
        $or: [
          { 'end_date:eq': null },
          { 'end_date:ne': null, 'end_date:gte': 'now()' }
        ],
        sort: 'updated_at:desc'
      }
    })

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

const fetchNewsSlider = async () => {
  try {
    const { data } = await http.get('content/news', {
      fields: [
        'uuid',
        'title',
        'image',
        'published_at',
        'updated_at',
        'chapo',
        'slug',
        'content_type',
        'is_featured',
        { reactions: ['count', { users: ['uuid'] }] },
        { comments: ['count'] },
        {
          news_categories: {
            fields: ['uuid', 'title'],
            filters: { 'status:eq': 1 }
          }
        }
      ],
      filters: {
        'status:eq': 1,
        'is_featured:eq': 1,
        sort: 'published_at:desc',
        'published_at:lte': 'now()',
        limit: 4
      }
    })

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

const fetchNewsListing = async () => {
  try {
    const { data } = await http.get('content/news', {
      fields: [
        'uuid',
        'title',
        'image',
        'published_at',
        'updated_at',
        'chapo',
        'slug',
        'content_type',
        'is_featured',
        { news_categories: ['uuid', 'title'] },
        { reactions: ['count', { users: ['uuid'] }] },
        { comments: ['count'] }
      ],
      filters: {
        'status:eq': 1,
        'is_featured:ne': 1,
        sort: 'published_at:desc',
        'published_at:lte': 'now()',
        limit: 4
      }
    })

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

export { fetchFlashInfos, fetchNewsSlider, fetchNewsListing }
