import { request } from './index';

// local storage keys
export const ACCESS_TOKEN_KEY = 'access_token';
export const REFRESH_TOKEN_KEY = 'refresh_token';

export type TokenType = string;

export async function getToken(): Promise<TokenType> {
  const accessToken = localStorage.getItem(ACCESS_TOKEN_KEY);
  if (accessToken) return accessToken;
  return await getFreshToken();
}

export async function getFreshToken(): Promise<TokenType> {
  const refreshToken = localStorage.getItem(REFRESH_TOKEN_KEY);
  if (!refreshToken) throw Error('Refresh token not found.');
  const data = await fetchFreshToken(refreshToken);
  localStorage.setItem(ACCESS_TOKEN_KEY, data.access);
  return data.access;
}

export type FetchTokenDataType = { mobile: string; password: string };
export type FetchTokenReturnType = { access: TokenType; refresh: TokenType };

export async function fetchToken({
  mobile,
  password
}: FetchTokenDataType): Promise<FetchTokenReturnType> {
  return await request(false, {
    method: 'POST',
    url: '/auth/login',
    data: { mobile, password }
  });
}

export type FetchFreshTokenDataType = { refresh: TokenType };
export type FetchFreshTokenReturnType = { access: TokenType };

export async function fetchFreshToken(token: TokenType): Promise<FetchFreshTokenReturnType> {
  return await request(false, {
    method: 'POST',
    url: '/auth/refresh',
    data: { refresh: token }
  });
}

export function logoutUser(): Promise<void> {
  return Promise.resolve();
}
