/*
 * 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, updateUserProfile } from './authSlice';
import { authAPI } from '../services/authAPI';
import { showError, showSuccess, showWarning } 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');
      
      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
        if(response.data.data.user.dashboard_role !=='radiologist'){
          showWarning('You are not authorized to access this application')
          return rejectWithValue('Not Authorized');
        }
        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 update user profile
 */
export const updateUserProfileAsync = createAsyncThunk(
  'auth/updateUserProfile',
  async (profileData: { first_name: string; last_name: string }, { getState, rejectWithValue, dispatch }) => {
    try {
      const state = getState() as any;
      const user = state.auth.user;
      const token = user?.access_token;
      
      if (!user?.user_id || !token) {
        return rejectWithValue('User not authenticated');
      }

      const response: any = await authAPI.updateUserProfile(user.user_id, profileData, token);
      
      if (response.ok && response.data) {
        // Update local state
        dispatch(updateUserProfile({
          first_name: profileData.first_name,
          last_name: profileData.last_name,
          display_name: `${profileData.first_name} ${profileData.last_name}`
        }));
        
        showSuccess('Profile updated successfully');
        return response.data;
      } else {
        const errorMessage = response.data?.message || response.problem || 'Failed to update profile';
        showError(errorMessage);
        return rejectWithValue(errorMessage);
      }
    } catch (error: any) {
      const errorMessage = error.message || 'Failed to update profile';
      showError(errorMessage);
      return rejectWithValue(errorMessage);
    }
  }
);

/**
 * Thunk to change password
 */
export const changePasswordAsync = createAsyncThunk(
  'auth/changePassword',
  async (passwordData: { currentPassword: string; newPassword: string }, { getState, rejectWithValue }) => {
    try {
      const state = getState() as any;
      const user = state.auth.user;
      const token = user?.access_token;
      
      if (!user?.user_id || !token) {
        return rejectWithValue('User not authenticated');
      }

      const response: any = await authAPI.changePassword(user.user_id, { password: passwordData.newPassword }, token);
      
      if (response.ok && response.data) {
        showSuccess('Password changed successfully');
        return response.data;
      } else {
        const errorMessage = response.data?.message || response.problem || 'Failed to change password';
        showError(errorMessage);
        return rejectWithValue(errorMessage);
      }
    } catch (error: any) {
      const errorMessage = error.message || 'Failed to change password';
      showError(errorMessage);
      return rejectWithValue(errorMessage);
    }
  }
);

/**
 * 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.
 */ 