import { createSlice } from "@reduxjs/toolkit";
import { LicenseOrderHistoryState } from "./state";
import { getLicenseOrderHistoriesAsync } from "./operations";
import { LIMIT_ORDER_HISORY_NUM } from "./constants";

const initialState: LicenseOrderHistoryState = {
  domain: {
    total: 0,
    orderHistories: [],
  },
  apps: {
    limit: LIMIT_ORDER_HISORY_NUM,
    offset: 0,
    isLoading: false,
    LicenseOrder: undefined,
  },
};

export const licenseOrderHistorySlice = createSlice({
  name: "licenseOrderHistory",
  initialState,
  reducers: {
    cleanupApps: (state) => {
      state.domain = initialState.domain;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getLicenseOrderHistoriesAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(
      getLicenseOrderHistoriesAsync.fulfilled,
      (state, action) => {
        state.domain.total = action.payload.total;
        state.domain.orderHistories = action.payload.orderHistories;
        state.apps.isLoading = false;
      }
    );
    builder.addCase(getLicenseOrderHistoriesAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export const { cleanupApps } = licenseOrderHistorySlice.actions;

export default licenseOrderHistorySlice.reducer;
