import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { PartnerLicensesState } from "./state";
import { PartnerLicenseInfo } from "../../../api/api";
import { getMyAccountAsync, getPartnerLicenseAsync } from "./operations";

const initialState: PartnerLicensesState = {
  domain: {
    total: 0,
    ownPartnerLicense: {
      accountId: 0,
      tier: 0,
      companyName: "",
      stockLicense: 0,
      issuedRequested: 0,
      shortage: 0,
      issueRequesting: 0,
    },
    childrenPartnerLicenses: [],
    acountInfo: { accountId: 0 },
  },
  apps: {
    limit: 1,
    offset: 0,
  },
};

export const partnerLicenseSlice = createSlice({
  name: "partnerLicense",
  initialState,
  reducers: {
    changeTotal: (state, action: PayloadAction<{ total: number }>) => {
      const { total } = action.payload;
      state.domain.total = total;
    },
    changeOwnPartnerLicense: (
      state,
      action: PayloadAction<{ ownPartnerLicense: PartnerLicenseInfo }>
    ) => {
      const { ownPartnerLicense } = action.payload;
      state.domain.ownPartnerLicense = ownPartnerLicense;
    },
    changeChildrenPartnerLicenses: (
      state,
      action: PayloadAction<{
        childrenPartnerLicenses: PartnerLicenseInfo[];
      }>
    ) => {
      const { childrenPartnerLicenses } = action.payload;
      state.domain.childrenPartnerLicenses = childrenPartnerLicenses;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(getMyAccountAsync.fulfilled, (state, action) => {
      state.domain.acountInfo = action.payload;
    });
    builder.addCase(getPartnerLicenseAsync.fulfilled, (state, action) => {
      state.domain.total = action.payload.total;
      state.domain.ownPartnerLicense = action.payload.ownPartnerLicense;
      state.domain.childrenPartnerLicenses =
        action.payload.childrenPartnerLicenses;
    });
  },
});
export const {
  changeTotal,
  changeOwnPartnerLicense,
  changeChildrenPartnerLicenses,
} = partnerLicenseSlice.actions;

export default partnerLicenseSlice.reducer;
