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

export const fetchOffersListing = async ({ $route }) => {
  const currentRoute = $route.path.replace(/^\/\w+\//, '')

  try {
    const { data } = await http.get('content/custom', {
      fields: ['uuid', 'title', 'content'],
      filters: {
        'status:eq': 1,
        'slug:eq': currentRoute
      }
    })

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

export const fetchOffer = async ({ $route }) => {
  try {
    const { data } = await http.get('content/offers', {
      fields: [
        'uuid',
        'published_at',
        'title',
        'chapo',
        'image',
        'slug',
        'content_type',
        'content',
        'localisations',
        'email_address',
        'admin',
        {
          offers_categories: {
            fields: ['uuid', 'title', 'image', 'color'],
            filters: { 'status:eq': 1 }
          }
        },
        { reactions: { users: ['uuid'] } }
      ],
      filters: {
        'status:eq': 1,
        sort: 'published_at:desc',
        'published_at:lte': 'now()',
        'slug:eq': $route.params.slug
      }
    })

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