import axios from 'axios'
import {setUser} from "../reducers/userR";

export const registration = async (email, password) => {
    try {
        const response = await axios.post(`http://localhost:4000/api/authorization/registration`, { email,password})
        alert(response.data.message)
    } catch (e) {
        console.log(e.response.data.message)
    }
}

export const login =  (email, password) => {
    return async dispatch => {
        try {
            const response = await axios.post(`http://localhost:4000/api/authorization/login`, {email,password})
            dispatch(setUser(response.data.user))
            localStorage.setItem('token', response.data.token)
        } catch (e) {
            console.log(e.response.data.message)
        }
    }
}

export const auth =  () => {
    return async dispatch => {
        try {
            const response = await axios.get(`http://localhost:4000/api/authorization/auth`,{headers:{Authorization:`Bearer ${localStorage.getItem('token')}`}})
            dispatch(setUser(response.data.user))
            localStorage.setItem('token', response.data.token)
        } catch (e) {
            localStorage.removeItem('token')
        }
    }
}