import { createSlice } from "@reduxjs/toolkit";
import { AcceptState } from "./state";
import {
  getAccountInfoMinimalAccessAsync,
  getTermsInfoAsync,
  updateAcceptedVersionAsync,
} from "./operations";

const initialState: AcceptState = {
  domain: {
    tier: 0,
    termsInfo: [
      {
        documentType: "",
        version: "",
      },
    ],
  },
  apps: {
    isLoading: false,
  },
};

export const termsSlice = createSlice({
  name: "terms",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getAccountInfoMinimalAccessAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(
      getAccountInfoMinimalAccessAsync.fulfilled,
      (state, actions) => {
        state.apps.isLoading = false;
        state.domain.tier = actions.payload.tier;
      }
    );
    builder.addCase(getAccountInfoMinimalAccessAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(getTermsInfoAsync.fulfilled, (state, actions) => {
      state.domain.termsInfo = actions.payload.termsInfo;
    });
    builder.addCase(updateAcceptedVersionAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(updateAcceptedVersionAsync.fulfilled, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(updateAcceptedVersionAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export default termsSlice.reducer;
