<template>
  <TemplateContainer class="franchised-space-folder-edition-page" size="s">
    <FolderForm />
  </TemplateContainer>
</template>

<script>
import TemplateContainer from '@inside-commons/components/lib/TemplateContainer'
import SpaceFolderForm from '../components/spaces/SpaceFolderForms'

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

const fetchSpace = async ({ $route }) => {
  try {
    const { uuid } = $route.query

    let space = $route.query.space.split('/')
    space = space[space.length - 1]

    const isEdition = !!uuid
    let folder = null

    if (isEdition) {
      const { data } = await http.get('content/franchised_spaces_folders', {
        fields: [
          'uuid',
          'title',
          { franchised_spaces_folders: ['uuid', 'title'] },
          { franchised_spaces: ['uuid', 'slug'] }
        ],
        filters: { 'uuid:eq': uuid }
      })

      folder = {
        uuid: data[0].uuid,
        title: data[0].title,
        parentFolder: data[0].franchised_spaces_folders || {}
      }

      space = data[0].franchised_spaces.slug[0]
    }

    if (!space) {
      return { error: true }
    }

    const { data } = await http.get('content/franchised_spaces', {
      fields: ['uuid', 'title', 'slug'],
      filters: { 'slug:eq': space }
    })

    if (!data[0]) {
      return { error: true }
    }

    return {
      error: false,
      space: data[0],
      isEdition,
      ...(isEdition && { folder })
    }
  } catch (err) {
    throw new Error(err)
  }
}

export default {
  name: 'FranchisedSpaceFolderEditionPage',
  components: {
    TemplateContainer,
    FolderForm: withFetch(SpaceFolderForm, { size: 'xxl' })(fetchSpace)
  }
}
</script>

<style lang="scss">
.franchised-space-folder-edition-page {
  margin-top: var(--spacing-3xl);
}
</style>
