import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import {
  removeAccessToken,
  initialConfig,
  loadAccessToken,
  saveAccessToken,
  loadRefreshToken,
  saveRefreshToken,
  removeRefreshToken,
} from "./utils";
import { AuthState } from "./state";

const initialState: AuthState = {
  configuration: initialConfig(),
  accessToken: loadAccessToken(),
  refreshToken: loadRefreshToken(),
};

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setToken: (
      state,
      action: PayloadAction<Omit<AuthState, "configuration">>
    ) => {
      const { accessToken, refreshToken } = action.payload;
      if (accessToken && refreshToken) {
        state.accessToken = accessToken;
        saveAccessToken(accessToken);

        state.refreshToken = refreshToken;
        saveRefreshToken(refreshToken);
      }
    },
    clearToken: (state) => {
      state.accessToken = null;
      state.refreshToken = null;
      removeAccessToken();
      removeRefreshToken();
    },
  },
});

export const { setToken, clearToken } = authSlice.actions;

export default authSlice.reducer;
