import { StorageDefaultURL, StoragePrivilege, WEB_URL, encryptData } from '@pos/base';
import { StorageAccessToken, StorageUserData, StorageActiveAccount } from '@pos/base';

export async function handleLogout(authParam?: string) {
  // INDEXED-DB
  await StorageUserData.delete(); //remove user data from indexed-db
  await StorageAccessToken.delete(); //remove access token from local indexed-db
  await StoragePrivilege.delete();

  //LOCAL STORAGE
  await StorageActiveAccount.delete(); // remove active account from local storage
  await StorageDefaultURL.delete();

  window.location.replace(
    `/auth/login${authParam ? `?u=${encodeURIComponent(encryptData(JSON.stringify(authParam)))}` : ''}`,
  );
}

export async function handleLogin(respLogin: any) {
  await StorageAccessToken.delete();
  try {
    // save user id to StorageActiveAccount on Local storage
    const userID = respLogin?.id; // adjust key "id" with key that have userID value
    await StorageActiveAccount.create({ value: userID });

    // save access token to StorageAccessToken
    const accessToken = respLogin?.token;
    await StorageAccessToken.create('Bearer ' + accessToken);

    // save user data information to
    const userData = respLogin; // adjustment with value user data
    await StorageUserData.create(userData);

    // find web url module for first menu to access
    await StorageDefaultURL.create({ value: WEB_URL.APP });

    // save default url to local storage
  } catch (error) {
    console.error(error);
  }
}
