import { client, gqlContext } from '@things-factory/shell'
import gql from 'graphql-tag'

export const fetchPageSettings = async function (variables = { codes, partners, settings, settingsDomain }) {
  try {
    const response = await client.query({
      query: gql`
        query pageSettings($codes: [Filter!], $partners: [Filter!], $settings: [Filter!], $settingsDomain: String) {
          pageSettings(codes: $codes, partners: $partners, settings: $settings, settingsDomain: $settingsDomain) {
            type
            details {
              id
              name
              description
              value
              settingDetails {
                id
                name
                description
                rank
              }
            }
          }
        }
      `,
      variables,
      context: gqlContext()
    })

    if (!response.errors && response.data.pageSettings) {
      return {
        codes: response.data.pageSettings.find(x => x.type == 'code')?.details || [],
        partners: response.data.pageSettings.find(x => x.type == 'partner')?.details || [],
        settings: response.data.pageSettings.find(x => x.type == 'setting')?.details || []
      }
    } else {
      return {
        code: [],
        partners: [],
        settings: []
      }
    }
  } catch (error) {
    console.log(error)
  }
}
