import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { LicenseOrdersState } from "./state";
import { orderLicenseAsync } from "./operations";

const initialState: LicenseOrdersState = {
  apps: {
    poNumber: "",
    newOrder: 0,
    isLoading: false,
  },
};
export const licenseSlice = createSlice({
  name: "license",
  initialState,
  reducers: {
    changePoNumber: (state, action: PayloadAction<{ poNumber: string }>) => {
      const { poNumber } = action.payload;
      state.apps.poNumber = poNumber.toUpperCase();
    },
    changeNewOrder: (state, action: PayloadAction<{ newOrder: number }>) => {
      const { newOrder } = action.payload;
      state.apps.newOrder = newOrder;
    },
    cleanupApps: (state) => {
      state.apps = initialState.apps;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(orderLicenseAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(orderLicenseAsync.fulfilled, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(orderLicenseAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
  },
});

export const { changePoNumber, changeNewOrder, cleanupApps } =
  licenseSlice.actions;

export default licenseSlice.reducer;
