import { IData } from "../../models/IData";
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { createSession, connectSession } from "./ActionCreator";

export interface sessionState {
  isLoading: boolean;
  error: any;
  url: string;
  id: string;
}

interface ConnectSessionResponseInterface {
  websocket_url: string;
}

interface CreateSessionResponseInterface {
  session_id: string;
}

const initialState: sessionState = {
  isLoading: false,
  error: "",
  url: "",
  id: "",
};

export const sessionSlice = createSlice({
  name: "data",
  initialState,
  reducers: {
    cleanErrors(state) {
      state.error = null;
    },
  },
  extraReducers: {
    [createSession.fulfilled.type]: (
      state,
      action: PayloadAction<CreateSessionResponseInterface>
    ) => {
      state.isLoading = false;
      state.id = action.payload.session_id;
    },
    [createSession.rejected.type]: (state, action: PayloadAction<any>) => {
      console.log(action.payload)
      state.isLoading = false;
      state.error = action.payload;
    },
    [createSession.pending.type]: (state) => {
      state.isLoading = true;
    },
    [connectSession.fulfilled.type]: (
      state,
      action: PayloadAction<ConnectSessionResponseInterface>
    ) => {
      state.isLoading = false;
      const url = action.payload.websocket_url.replace("wss://", "https://");
      state.url = url;
    },
    [connectSession.rejected.type]: (state, action: PayloadAction<any>) => {
      state.isLoading = false;
      state.error = action.payload;
    },
    [connectSession.pending.type]: (state, action) => {
      state.isLoading = true;
    },
  },
});

export default sessionSlice.reducer;
