/*
 * 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 { logout } from './authSlice';
import { authAPI } from '../services/authAPI';
import { showError, showSuccess } from '../../../shared/utils/toast';

/**
 * Thunk to login user
 */
export const login = createAsyncThunk(
  'auth/login',
  async (credentials: { email: string; password: string }, { rejectWithValue }) => {
    try {
      const response:any = await authAPI.login(credentials.email, credentials.password,'web');
      console.log('user response',response)
      
      if(response.data.message && !response.data.success){
        showError(response.data.message)
        return rejectWithValue(response.data.message);
      }
      
      if(response.data.message && response.data.success){
        showSuccess(response.data.message)
      }
      
      if (response.ok && response.data && response.data.data) {
        // Return the user data for the fulfilled case
        return {...response.data.data.user,access_token:response.data.data.access_token};
      } else {
        const errorMessage = response.data?.message || response.problem || 'Unknown error';
        return rejectWithValue(errorMessage);
      }
    } catch (error: any) {
      return rejectWithValue(error.message);
    }
  }
);


/**
 * Thunk to logout user
 */
export const logoutUser = createAsyncThunk(
  'auth/logout',
  async (_, { dispatch, rejectWithValue }) => {
    try {
      // TODO: Add logout API call if needed
      // const response = await authAPI.logout();
      
      // For now, just dispatch the logout action
      dispatch(logout());
      
      // Show success message
      showSuccess('Logged out successfully');
      
      return true;
    } catch (error: any) {
      console.error('Logout error:', error);
      return rejectWithValue(error.message);
    }
  }
);

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