import { actionAuthLogin } from '../Redux/auth_reducer';
import { actionLoginNetworkError, actionLoginNetworkErrorReset } from '../Redux/network_reducer';
import {actionPromise} from '../Redux/promise_reducer';

const urlConst = '/graphql';

const getGQL = (url) => (query, variables = {}) => {
    return fetch(url, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            ...(localStorage.authToken ? { Authorization: `Bearer ${localStorage.authToken}` } : {}),
        },
        body: JSON.stringify({ query, variables }),
    }).then((res) => res.json());
};

export const gql = getGQL(urlConst);

// export const actionLogin = async (login, password) => {
//     store.dispatch(actionPromise('Login', gql(`query Login($loginStr: String!, $passwordStr: String!){
//                 login(login: $loginStr, password: $passwordStr)
//             }`, 
//             {
//                 "loginStr": "Pocu46",
//                 "passwordStr": "a190689"
//             })
//         )
//     )
//     // console.log(resLogin)
// }
export const actionLogin = (login, password) => async (dispatch) => {
    console.log(login, password)
    let result = await dispatch(actionPromise('Login', gql(`query Login($loginStr: String!, $passwordStr: String!){
                login(login: $loginStr, password: $passwordStr)
            }`, 
            {
                "loginStr": login,
                "passwordStr": password
            })
        )
    )
    if(result?.data?.login) {
        console.log(result.data.login)
        dispatch(actionAuthLogin(result.data.login))
    } else {
        console.log("Authorization failed")
        dispatch(actionLoginNetworkError())
        setTimeout(() => {actionLoginNetworkErrorReset()}, 5000)
    }
}