import { PayloadAction, createSlice } from "@reduxjs/toolkit";
import { TemplateState } from "./state";
import { listTemplateAsync, uploadTemplateAsync } from "./operations";

const initialState: TemplateState = {
  apps: {
    isLoading: false,
    isUploading: false,
    uploadFile: undefined,
  },
  domain: {},
};

export const templateSlice = createSlice({
  name: "template",
  initialState,
  reducers: {
    cleanupTemplate: (state) => {
      state.apps.uploadFile = initialState.apps.uploadFile;
    },
    changeUploadFile: (state, action: PayloadAction<{ file: File }>) => {
      const { file } = action.payload;
      state.apps.uploadFile = file;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(listTemplateAsync.pending, (state) => {
      state.apps.isLoading = true;
    });
    builder.addCase(listTemplateAsync.fulfilled, (state, action) => {
      const { templates } = action.payload;

      state.domain.templates = templates;
      state.apps.isLoading = false;
    });
    builder.addCase(listTemplateAsync.rejected, (state) => {
      state.apps.isLoading = false;
    });
    builder.addCase(uploadTemplateAsync.pending, (state) => {
      state.apps.isUploading = true;
    });
    builder.addCase(uploadTemplateAsync.fulfilled, (state) => {
      state.apps.isUploading = false;
    });
    builder.addCase(uploadTemplateAsync.rejected, (state) => {
      state.apps.isUploading = false;
    });
  },
});

export const { changeUploadFile, cleanupTemplate } = templateSlice.actions;

export default templateSlice.reducer;
