import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { LicenseOrderHistoryState } from "./state";
import {
  getLicenseOrderHistoriesAsync,
  issueLicenseAsync,
  cancelOrderAsync,
  cancelIssueAsync,
} from "./operations";
import { LIMIT_ORDER_HISORY_NUM } from "./constants";

const initialState: LicenseOrderHistoryState = {
  domain: {
    total: 0,
    orderHistories: [],
    companyName: "",
  },
  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;
    },
    savePageInfo: (
      state,
      action: PayloadAction<{
        limit: number;
        offset: number;
      }>
    ) => {
      const { limit, offset } = action.payload;
      state.apps.limit = limit;
      state.apps.offset = offset;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getLicenseOrderHistoriesAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(
      getLicenseOrderHistoriesAsync.fulfilled,
      (state, action) => {
        state.domain.total = action.payload.histories.total;
        state.domain.orderHistories = action.payload.histories.orderHistories;
        state.domain.companyName = action.payload.companyName;
        state.apps.isLoading = false;
      }
    );
    builder.addCase(getLicenseOrderHistoriesAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(issueLicenseAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(issueLicenseAsync.fulfilled, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(issueLicenseAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(cancelOrderAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(cancelOrderAsync.fulfilled, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(cancelOrderAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(cancelIssueAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(cancelIssueAsync.fulfilled, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(cancelIssueAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export const { cleanupApps, savePageInfo } = licenseOrderHistorySlice.actions;

export default licenseOrderHistorySlice.reducer;
