import { createSlice, PayloadAction } from "@reduxjs/toolkit";

export type User = {
  uuid: string;
  firstName: string;
  lastName: string;
  mobileNumber: string;
  dialCode: string;
  email: string;
  role?: string[];
  apiKey?: string;

  profilePicture?: string;

  isVerified?: boolean;
  balance?: number;
};

interface IInitialState {
  user: User;
  token: string | null;
  refreshToken: string | null;
}

const initialState: IInitialState = {
  user: null,
  token: null,
  refreshToken: null,
};

export const userSlice = createSlice({
  name: "user",
  initialState,

  reducers: {
    setUser: (state, action) => {
      state.user = action.payload.user;
      state.token = action.payload.token;
      state.refreshToken = action.payload.refreshToken;
    },
    clearUser: (state) => {
      state.user = null;
      state.token = null;
      state.refreshToken = null;
    },

    setStateUser: (state, action) => {
      state.user = action.payload;
    },

    updateUser: (state, action: PayloadAction<Partial<User>>) => {
      if (!state.user) return;

      state.user = {
        ...state.user,
        ...action.payload,
        profilePicture:
          action.payload.profilePicture === ""
            ? "/images/user-default.svg"
            : action.payload.profilePicture
              ? action.payload.profilePicture
              : state.user.profilePicture,
      };
    },

    setToken: (state, action) => {
      state.token = action.payload;
    },

    setRefreshToken: (state, action) => {
      state.refreshToken = action.payload;
    },
  },
});

export const {
  setUser,
  clearUser,
  setToken,
  setRefreshToken,
  setStateUser,
  updateUser,
} = userSlice.actions;
export default userSlice.reducer;
