import { createSlice } from "@reduxjs/toolkit";
import { VerifyState } from "./state";
import { userVerifyAsync, verifyAsync } from "./operations";

const initialState: VerifyState = {
  apps: {
    VerifyState: "duringVerify",
  },
};

export const verifySlice = createSlice({
  name: "verify",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    // アカウント登録
    builder.addCase(verifyAsync.pending, (state) => {
      state.apps.VerifyState = "duringVerify";
    });
    builder.addCase(verifyAsync.fulfilled, (state) => {
      state.apps.VerifyState = "success";
    });
    builder.addCase(verifyAsync.rejected, (state, action) => {
      const { payload } = action;

      // メール認証済みかをエラーコードから判定
      if (payload?.error.code === "E010202") {
        state.apps.VerifyState = "alreadySuccess";
      } else {
        state.apps.VerifyState = "failed";
      }
    });
    // ユーザ追加
    builder.addCase(userVerifyAsync.pending, (state) => {
      state.apps.VerifyState = "duringVerify";
    });
    builder.addCase(userVerifyAsync.fulfilled, (state) => {
      state.apps.VerifyState = "success";
    });
    builder.addCase(userVerifyAsync.rejected, (state, action) => {
      const { payload } = action;

      // メール認証済みかをエラーコードから判定
      if (payload?.error.code === "E010202") {
        state.apps.VerifyState = "alreadySuccess";
      } else {
        state.apps.VerifyState = "failed";
      }
    });
  },
});

export default verifySlice.reducer;
