<template>
  <div class="homepage-dashboard-container">
    <HomepageBlockWrapperContainer />
  </div>
</template>

<script>
import { http } from '@inside-library/helpers/Http'
import { withFetch } from 'inside-collection/hocs'
import HomepageBlockWrapper from './HomepageBlockWrapper'
import { storage } from '@inside-library/helpers/Storage'

const fetchBlockDashboard = async () => {
  try {
    let fields = []

    for (let i = 1; i < 12; i++) {
      fields = fields.concat([
        `block_${i}_title`,
        `block_${i}_text`,
        `block_${i}_kpi`,
        `block_${i}_modal_file`,
        `block_${i}_modal_text`
      ])
    }

    const site = storage.get('site') || {}
    const client = storage.get('client') || {}

    const { data } = await http.get(
      'content/dashboards',
      {
        fields: ['uuid', 'title', 'admin', 'content_type', ...fields],
        filters: {
          'status:eq': 1,
          sort: 'published_at:desc',
          limit: 1,
          ...(site.uuid && {
            sites: {
              uuid: site.uuid
            }
          }),
          ...(client.machine_name && {
            clients: {
              machine_name: client.machine_name
            }
          })
        }
      },
      { useLangcode: true }
    )

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

export default {
  name: 'homepage-dashboard',
  components: {
    HomepageBlockWrapperContainer: withFetch(HomepageBlockWrapper, {
      size: 'xxl'
    })(fetchBlockDashboard)
  }
}
</script>

<style lang="scss"></style>
