import {actionPromise} from "../reducers/PromiseReducer";
import {gql} from "./PathDB";
import {actionCategoryChange, actionCategoryCreate} from "../reducers/CategoryReducer";

//CategoryFind -- parent: null
export const actionRootCats = () => {
    return actionPromise('rootCats', gql(`query rootCats{
          CategoryFind(query: "[{\\"parent\\": null}]"){
            _id
            name
            subCategories{
              _id,
              name,
              subCategories{
                _id,
                name
              }
            }
          }
        }`)
    )
}
export const actionFullRootCats = () =>
    async dispatch => {
        let value = await dispatch(actionRootCats())
        if (value){
            dispatch(actionCategoryCreate(value))
        }
    }

//CategoryFindOne
const actionCatById = (_id) => {
    return actionPromise('catById', gql(`query catById($q: String){
            CategoryFindOne(query: $q){
                _id goods {
                    _id createdAt name description price images {
                        url
                    }
                }
            }
        }`, {q: JSON.stringify([{_id}])}))
}
export const actionFullCatById = (_id) =>
    async dispatch => {
        let value = await dispatch(actionCatById(_id))
        if (value){
            dispatch(actionCategoryChange(value))
        }
    }

//CategoryCount
export const actionCategoryCount = () => {
    return actionPromise('categoryCount', gql(`query categoryCount{
            CategoryCount(query: "[{}]")
          }`
        )
    )
}

//CategoryUpsert
export const actionCategoryUpsert = (category) => {
    const mainTitleCategory = category[0]?.name || 'No name';
    const mainGoodsCategory = []
    if (category[0]?.goods && category[0]?.goods?.length > 0){
        category[0].goods.forEach(item => {
            mainGoodsCategory.push(...item)
        })
    }

    console.log(mainTitleCategory, mainGoodsCategory)
    return actionPromise('categoryUpsert', gql(`
                mutation categoryUpsert($name: String!){
                CategoryUpsert(category: {name: $name}) {
                    _id
                    createdAt
                    name
                }
            }`,{name: mainTitleCategory}
        )
    )
}

//CategoryFind
export const actionAllCategory = () => {
    return actionPromise('allCategory', gql(`query allCategory{
          CategoryFind(query: "[{}]"){
            _id
            name
            subCategories{
              _id,
              name,
              subCategories{
                _id,
                name
              }
            }
          }
        }`)
    )
}
export const actionFullAllCategory = () =>
    async dispatch => {
        let value = await dispatch(actionAllCategory())
        if (value){
            dispatch(actionCategoryCreate(value))
        }
    }
