import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { sendRpcRequest } from "../../services/apiClient";
import { TG_USER_ID } from "../../constants/constants";

interface ISession {
  login: string;
  emailVerified: boolean;
  subDateEnd: string;
}

interface IAccountState {
  session: ISession;
  loading: boolean;
  isCheckPasswordLoading: boolean;
  errorCheckPassword: string | null;
}

const initialState: IAccountState = {
  session: {
    login: "",
    emailVerified: false,
    subDateEnd: "",
  },
  loading: false,
  isCheckPasswordLoading: false,
  errorCheckPassword: null,
};

export const accountSession = createAsyncThunk(
  "account/session",
  async (_, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<ISession>("account.session");

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }

      return rejectWithValue("Unknown error occurred");
    }
  }
);

export const checkPassword = createAsyncThunk(
  "account/checkPassword",
  async (password: string, { rejectWithValue }) => {
    try {
      const response = await sendRpcRequest<{
        message: string;
        success: boolean;
      }>("account.checkpwd", {
        password,
      });

      if (response?.message === "valid") {
        const deleteAccountResponse = await sendRpcRequest<{
          message: string;
          success: boolean;
        }>("account.deleteaccount");

        if (deleteAccountResponse.success) {
          localStorage.removeItem(`token-${TG_USER_ID}`);
          localStorage.removeItem(`pincode-${TG_USER_ID}`);
          sessionStorage.removeItem(`pincode-${TG_USER_ID}`);
          window.location.href = "/";
        }

        return response;
      }

      return response;
    } catch (error: unknown) {
      if (typeof error === "object" && error !== null && "message" in error) {
        return rejectWithValue(error.message);
      }
      return rejectWithValue("Unknown error occurred");
    }
  }
);

const accountSlice = createSlice({
  name: "account",
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(accountSession.pending, (state) => {
        state.loading = true;
      })
      .addCase(accountSession.fulfilled, (state, action) => {
        state.loading = false;
        state.session = action.payload;
      })
      .addCase(accountSession.rejected, (state) => {
        state.loading = false;
      })

      .addCase(checkPassword.pending, (state) => {
        state.isCheckPasswordLoading = true;
      })
      .addCase(checkPassword.fulfilled, (state) => {
        state.isCheckPasswordLoading = false;
        state.errorCheckPassword = null;
      })
      .addCase(checkPassword.rejected, (state, action) => {
        state.isCheckPasswordLoading = false;
        state.errorCheckPassword = action.payload as string;
      });
  },
});

export default accountSlice.reducer;
