import { Dispatch, Action } from 'redux';
import { ThunkAction } from 'redux-thunk';
import {
  LOGIN_USER_REQUEST,
  LOGIN_USER_SUCCESS,
  LOGIN_USER_FAILURE,
  GET_DATA_USER_LOGIN_AUTH,
  LoginUserRequestAction,
  LoginUserSuccessAction,
  LoginUserFailureAction
} from '../../../../constants/auth/login/Login';
import { RootState } from '../../../store/store';

const API_URL = process.env.REACT_APP_API_BASE_URL;

export const loginUserRequest = (): LoginUserRequestAction => ({
  type: LOGIN_USER_REQUEST
});

export const loginUserSuccess = (data: any): LoginUserSuccessAction => ({
  type: LOGIN_USER_SUCCESS,
  payload: data
});

export const loginUserFailure = (error: string): LoginUserFailureAction => ({
  type: LOGIN_USER_FAILURE,
  payload: error
});

export const loginUser = (
  values: {
    email: string,
    contrasena: string
  }): ThunkAction<
    Promise<void>,
    RootState,
    unknown,
    Action<string>
  > => async (dispatch: Dispatch) => {

    let response = null;

    try {
      const res = await fetch(API_URL + 'auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values),
      })
        .then(res => {
          if (res.status !== 200) {
            return {
              respuesta: false
            }
          } else {
            return res.json()
          }
        })

      if (res.respuesta) {
        dispatch({
          type: GET_DATA_USER_LOGIN_AUTH,
          payload: { ...res.user }
        });
        localStorage.setItem('token', res.token)
      }

      response = res
    } catch (error) {
      console.error('Error al iniciar sesión', error);
      localStorage.clear();
    }

    return response;
  };