import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
import { Token, LoginParams } from './types';
import pickBy from 'lodash/pickBy';
import identity from 'lodash/identity';

function replacer(key:string, value:string) {
  console.log(typeof value);
  if (key === 'token') {
    console.log(value, 'json');
    localStorage.setItem('token', JSON.stringify(value));
  } else { console.log(value, 'json')}
}

interface MyObj {
  token: string;
  error: string;
}

export const fetchToken = createAsyncThunk<Token[], LoginParams>(
  'token/fetchTokenStatus',
  async (params) => {
    const { login, password } = params;
    const { data } = await axios.post<Token[]>('/api/login', {
      params: pickBy(
        {
          login: login,
          password: password,
        },
        identity,
      ),
    });
    JSON.stringify(data[0], replacer);
    let obj: MyObj = JSON.parse(JSON.stringify(data));
    console.log(obj.token);
    console.log(obj.error);
    localStorage.setItem('token', JSON.stringify(Object.values(data)));
    console.log(Object.values(data), 4444);
    return data;
  },
);
