/*
 * File: authActions.ts
 * Description: Async actions (thunks) for Auth state
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */

import { createAsyncThunk } from '@reduxjs/toolkit';
import { loginStart, loginSuccess, loginFailure } from './authSlice';
import { authAPI } from '../services/authAPI';

/**
 * Thunk to login user
 */
export const login = createAsyncThunk(
  'auth/login',
  async (credentials: { email: string; password: string }, { dispatch, rejectWithValue }) => {
    try {
      dispatch(loginStart());
      const response:any = await authAPI.login(credentials.email, credentials.password,'web');
      console.log('user response',response)
      if (response.ok && response.data &&response.data.data) {
        //@ts-ignore
        dispatch(loginSuccess({...response.data.data.user,access_token:response.data.data.access_token}));
      } else {
        dispatch(loginFailure(response.problem || 'Unknown error'));
        return rejectWithValue(response.problem || 'Unknown error');
      }
    } catch (error: any) {
      dispatch(loginFailure(error.message));
      return rejectWithValue(error.message);
    }
  }
);

/*
 * End of File: authActions.ts
 * Design & Developed by Tech4Biz Solutions
 * Copyright (c) Spurrin Innovations. All rights reserved.
 */ 