

import { Routes, Route } from "react-router-dom";
import { RouteDefinitions } from "./RouteDefinitions";
import { useDispatch } from "react-redux";
import { getSessionDataFromCommon } from "../redux/thunks/userThunk";
import { decryptToObject } from "../utils/others";
import { sessionStore } from "../utils/sessionUtils";
import { useEffect } from "react";


//This is where We Get SessionUrlCode By Tamilselvan
const SessionCode = import.meta.env.ENV_SESSION_CODE


const generateRoutes = (routes) =>
  routes.map(({ path, element, children, index }, routeIndex) => (
    <Route key={path || `route-${routeIndex}`} path={path} element={element} index={index}>
      {children && generateRoutes(children)}
    </Route>
  ));

export default function AppRoutes() {
  const dispatch = useDispatch()
  useEffect(() => {
    const init = async () => {
      try {
        const qrResponse = await dispatch(
          getSessionDataFromCommon(SessionCode)
        ).unwrap();
        if (qrResponse?.data?.statusCode == 1) {
          const urldata = decryptToObject(qrResponse.data.data?.[0]?.OldUrl);

          console.log("Decrypted URL Data:", urldata);

          sessionStore("AppId", urldata?.AppId);
          sessionStore("CompId", urldata?.CompId);
          sessionStore("UserId", urldata?.UserId);
          sessionStore("UserType", urldata?.UserType);
          sessionStore("MobileNo", urldata?.MobileNo);
          sessionStore("SessionId", urldata?.SessionId);

          if (urldata?.BranchId) sessionStore("BranchId", urldata?.BranchId);

          sessionStorage.setItem("auth", urldata?.auth);
        }


      }
      catch (err) {

      }

    };

    init();
  }, []);
  const routes = generateRoutes(RouteDefinitions);
  return <Routes>{routes}</Routes>;
}
