import { all, takeLatest, call } from "@redux-saga/core/effects";
import { putRequest } from "../../request";
import { attemptRegister } from "../../request/registerRequest";
import { REGISTER_USER_FETCH } from "../actions/register/registerActionConstants";
import {
  fetchRegisterUserError,
  fetchRegisterUserSuccess,
} from "../actions/register/registerActions";

function* fetchRegisterUser({ payload }) {
  try {
    let requestData = {
      email: payload.values.mail.toString(),
      password: payload.values.password.toString(),
      image: payload.values.image
        .replace("data:image/jpeg;base64,", "")
        .replace("data:image/jpg;base64,", "")
        .replace("data:image/png;base64,", ""),
      company: {
        name: payload.values.nameOfFirm.toString(),
        PIB: payload.values.PIB.toString(),
        contacts: {
          telephone: payload.values.phoneNumber.toString(),
          location: payload.values.location.toString(),
          web: payload.values.website.toString(),
        },
      },
    };
    if (payload.values.phoneNumber?.length === 0)
      delete requestData.company.contacts.telephone;
    if (payload.values.location?.length === 0)
      delete requestData.company.contacts.location;
    if (payload.values.website?.length === 0)
      delete requestData.company.contacts.web;
    yield call(attemptRegister, requestData);
    console.log("jos nije crash");
    if (payload.handleResponseSuccess) {
      yield call(payload.handleResponseSuccess);
    }
    yield putRequest(fetchRegisterUserSuccess());
  } catch (e) {
    console.log(e);
    let type = "server";
    if (
      e?.response?.data?.toString() === "User with email already exists" ||
      e?.response?.data?.toString() === '"email" must be a valid email'
    ) {
      type = "mail";
    } else if (
      e?.response?.data?.toString() === "Company with PIB already exists"
    ) {
      type = "PIB";
    }
    const error = {
      error: e,
      type,
    };
    if (payload.handleResponseError) {
      yield call(payload.handleResponseError, error);
    }
    yield putRequest(fetchRegisterUserError());
  }
}

export default function* registerSaga() {
  yield all([takeLatest(REGISTER_USER_FETCH, fetchRegisterUser)]);
}
