import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { sendRpcRequest } from "../../services/apiClient";

interface ISession {
  login: string;
  emailVerified: boolean;
  subDateEnd: string;
}

interface IAccountState {
  session: ISession;
  loading: boolean;
}

const initialState: IAccountState = {
  session: {
    login: "",
    emailVerified: false,
    subDateEnd: "",
  },
  loading: false,
};

export const accountSession = createAsyncThunk(
  "account/session",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<ISession>("account.session");

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }

      return rejectWithValue("Unknown error occurred");
    }
  }
);

const accountSlice = createSlice({
  name: "account",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(accountSession.pending, (state) => {
        state.loading = true;
      })
      .addCase(accountSession.fulfilled, (state, action) => {
        state.loading = false;
        state.session = action.payload;
      })
      .addCase(accountSession.rejected, (state) => {
        state.loading = false;
      });
  },
});

export default accountSlice.reducer;
