import { setWithExpiry } from "../../logic/loigicUtils";
import { AccountInfo } from "../../services/auth/types";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";

const accountSlice = createSlice({
  name: "account",
  initialState: {
    account: null,
  },
  reducers: {
    accountLogin: (state, action: PayloadAction<AccountInfo>) => {
      setWithExpiry("token", action.payload.accessToken);
      setWithExpiry("refreshToken", action.payload.refreshToken);
      setWithExpiry("accountInfo", action.payload);
      return {
        ...state,
        account: action.payload,
      };
    },
    accountLogout: (state) => {
      localStorage.removeItem("token");
      localStorage.removeItem("refreshToken");
      localStorage.removeItem("accountInfo");
      localStorage.removeItem("selectedPartner");
      localStorage.removeItem("selectedLanguage");
      return {
        ...state,
        account: null,
      };
    },
  },
});

export const { accountLogin, accountLogout } = accountSlice.actions;
export default accountSlice.reducer;
