import {
  actionLogInSuccess,
  actionLogInReject,
  actionLogOutSuccess,
  actionLogOutReject,
  actionCurrentSuccess,
  actionCurrentReject
} from '../action';
import { setToken, loginUser, logoutUser, updateCredentials, updateUserAvatar, currentUser } from '../../../api-data';
import { IAuthorizationState } from '../../../typescript/redux/authorization/interfaces'
import { TResPromiseAll } from '../../../typescript/redux/authorization/types'

const asyncCreateUser = (name:string, lastName: string,file:object) => async (dispatch:any) => {
  try {
    const formData: any = new FormData()
    formData.append("avatar", file);
    const data = await Promise.all<TResPromiseAll>(
    [updateUserAvatar(formData), updateCredentials({ name, lastName, originalName:name, originalLastName:lastName})])
    const token = data.find(el => el?.token)?.token
    token&&dispatch(actionLogInSuccess(token))
  } catch (e) {
    dispatch(actionLogInReject())
  } 
};

const asyncLogin = (number:string, code: string,cb:() => void ) => async (dispatch:any) => {
  try {
    const data = await loginUser<{ token: string, registered: boolean }>(number, code);
    const token = data?.token
    const registered = data?.registered
    if (!token) return
    setToken.set(token)
    if (!registered) return cb()
    dispatch(actionLogInSuccess(token))
  } catch (e) {
    dispatch(actionLogInReject());
    cb()
  } 
};

const asyncLogout = () => async (dispatch:any) => {
  try {
    await logoutUser<object>();
    dispatch(actionLogOutSuccess());
    setToken.unset()
  } catch (e) {
    dispatch(actionLogOutReject());
  } 
};

const asyncCurrentUser = () => async (dispatch:any) => {
  try {
    const data = await currentUser<IAuthorizationState>()
    data && dispatch(actionCurrentSuccess(data));
    if(!data?.token) throw new Error('old token')
  } catch (e) {
    dispatch(actionCurrentReject());
  } 
};

export { asyncCreateUser, asyncLogin, asyncLogout, asyncCurrentUser };
