function getGQL(url) {
    return async (query, variables) => {
        let options = {
            method: 'POST',
            headers: {
                "Content-Type": "application/json",
                ...(localStorage.authToken ? { "Authorization": "Bearer " + localStorage.authToken } : {})
            },
            body: JSON.stringify({ query, variables })
        }

        try {
            let response = await fetch(url, options)
            let { data } = await response.json()
            return data[Object.keys(data)[0]]
        } catch (e) {
            throw new Error('an eror occured', e)
        }
    }
}

async function getCathegoryById(_id) {
    let gql = await getGQL(endpoint)
    return await gql(`
        query catById($query:String){
            CategoryFindOne(query:$query){
                name 
                goods{
                    _id name
                }
            }
        }`, 
        { query: JSON.stringify([{ _id }]) }
    )
}

async function loginAndToken(log, pass) {
    let gql = await getGQL(endpoint)
    return await gql(`
        query log($login:String, $password:String) {
            login(login: $login, password: $password)
        }`, 
        { login: log, password: pass }
    )
}

async function registerUser(log, pass, nick = 'user') {
    let gql = await getGQL(endpoint)
    return await gql(`
        mutation register($login:String, $password:String, $nick:String) {
            UserUpsert(
                user: { login: $login, password: $password, nick: $nick }
            ){
               nick login _id 
            }
        }`, 
        { login: log, password: pass, nick: nick }
    )
}

async function goodsList() {
    let gql = await getGQL(endpoint)
    return await gql(`
        query {
            GoodFind(query: "[{}]") {
                _id name categories{
                _id name
                }
            }
        }`
    )
}

async function ordersList() {
    let gql = await getGQL(endpoint)
    return await gql(`
        query {
            OrderFind(query:"[{}]"){
                _id total orderGoods{
                    count good{
                        _id name
                    }
                    owner{
                        _id login nick  
                    }
                }
            }
        }
    `)
}

async function newOrder(quantity, _id) {
    let gql = await getGQL(endpoint)
    return await gql(`
        mutation newOrder($count:Int!, $id:ID){
            OrderUpsert(
                order:{
                  orderGoods: [ {count: $count, good:{_id: $id}} ]
                }
            ) { _id createdAt total }
        }`, 
        { count: quantity, id: _id }
    )
}

async function getOrderById(_id) {
    let gql = await getGQL(endpoint)
    return await gql(`
        query order ($query:String) {
            OrderFindOne(query:$query) {
                _id 
                total 
                orderGoods {
                    count 
                    good {
                        name
                    }
                }
            }
        }`, 
        { query: JSON.stringify([{ _id }]) }
    )
}

async function getUserById(_id) {
    let gql = await getGQL(endpoint)
    return await gql(`
        query findUserById($query:String){
            UserFindOne(query:$query) {
            _id nick login
            }
        }`, 
        { query: JSON.stringify([{ _id }]) }
    )
}

let endpoint = 'http://shop-roles.asmer.fs.a-level.com.ua/graphql';

(async () => {
    localStorage.authToken = ''
    //Тут вставить какой-то кучерявый ник что бы зарегало юзера else = null
    console.log('New user', await registerUser("OLDBOY1338", "123", "asdasd"))
    localStorage.authToken = await loginAndToken("OLDBOY228", "3321")
    console.log('getCathegoryById', await getCathegoryById("5dc94bd00e36db246e3049ee")) //id для питсы
    console.log('All goods', await goodsList()) //список всех товаров + категории 
    console.log('All orders', await ordersList())
    console.log('Make order', await newOrder(3, "5dc888d20e36db246e3049c5"))
    console.log('Get order by id', await getOrderById("61aa7fb6c750c12ba6ba41fb"))
    console.log('Get user by id', await getUserById("61aa9c7ac750c12ba6ba4238")) //айдишник OLDBOY1338
})()
