import { JwtToken, ZodJwtToken } from '@/back-api';
import { environment } from '@/environment';
import { getApplicationLocation } from '@/utils/applPath';

export function b64_to_utf8(str: string): string {
  try {
    return decodeURIComponent(window.atob(str));
  } catch (ex) {
    console.log(`fail to decode "${str}"`);
    return '';
  }
}

export function utf8_to_b64(str: string): string {
  // remove unneeded "=" padding
  return window.btoa(encodeURIComponent(str)).replace('=', '');
}

/**
 * Request SSO connection
 */
export function hashLocalData(data?: string): string {
  if (
    !!data &&
    ![
      '',
      'null',
      'NULL',
      'undefined',
      '---',
      'unregistered',
      'unregistered/',
      'forbidden',
      'forbidden/',
    ].includes(data)
  ) {
    return utf8_to_b64(data);
  }
  const pathName = getApplicationLocation();
  if (['sso', '/sso', '/sso/'].includes(pathName)) {
    return utf8_to_b64('home');
  }
  if (
    !!pathName &&
    [
      '',
      'null',
      'NULL',
      'undefined',
      '---',
      'unregistered',
      'unregistered/',
      'forbidden',
      'forbidden/',
    ].includes(pathName)
  ) {
    return utf8_to_b64(pathName);
  }
  return utf8_to_b64('home');
}
/**
 * Request SSO connection
 */
export function unHashLocalData(data: string): string | undefined {
  if (!!data || ['', 'null', 'NULL', 'undefined', '---'].includes(data)) {
    return undefined;
  }
  try {
    return b64_to_utf8(data);
  } catch (ex) {
    console.error(`Can not convert the data: '${data}' ==> err=${ex}`);
  }
  return undefined;
}
const convertBase64asJson = (data: string) => {
  try {
    const jsonBuffer = b64_to_utf8(data);
    return JSON.parse(jsonBuffer);
  } catch (e) {
    console.error(`FAil to convert base64 data: ${e}`);
  }
};

export function parseToken(token: string): JwtToken {
  const parts = token.split('.');
  if (parts.length !== 3) {
    console.error(`Wrong token model ${token}`);
    throw new Error('Token JWT invalid');
  }
  const result = {
    header: convertBase64asJson(parts[0]),
    payload: convertBase64asJson(parts[1]),
    signature: parts[2],
  };
  return ZodJwtToken.parse(result);
}

/**
 * Request Open SSO Global website
 */
export function requestOpenSite(): void {
  window.location.href = environment.ssoSite;
}
/**
 * Request SSO connection
 */
export function requestSignIn(name?: string): void {
  console.log(
    `Request sign-in: '${environment.ssoSignIn}' + '${hashLocalData(name)}'`
  );
  window.location.href = environment.ssoSignIn + hashLocalData(name) + "/";
}
/**
 * Request SSO Disconnect
 */
export function requestSignOut(name?: string): void {
  const url = environment.ssoSignOut + hashLocalData(name);
  console.log(`Request just to the SSO: ${url}`)
  // unlog from the SSO
  window.location.href = url;
}
/**
 * Request SSO signUp
 */
export function requestSignUp(name?: string): void {
  const url = environment.ssoSignUp + hashLocalData(name);
  console.log(`Request just to the SSO: ${url}`)
  // unlog from the SSO
  window.location.href = url;
}
