import { request } from "./axios";
import { localStorage } from "@flare/js-utils";

const { setItem, getItem, removeItem } = localStorage;

const storageKeys = {
  TOKEN: "AUTHORIZATION_TOKEN",
  USER: "USER_NAME"
};

const authenticate = async (userName, password) => {
  const urlTemplate = process.env.REACT_APP_IDENTITY_AUTHENTICATION_URL;
  const url = urlTemplate
    .replace("{username}", userName)
    .replace("{password}", password);
  const options = {
    method: "post"
  };

  const response = await request(url, options);
  if (response.status === "SUCCESS") {
    setItem(storageKeys.TOKEN, response.token);
    setItem(storageKeys.USER, userName);
  }

  return response;
};

const invalidate = () => {
  const token = getItem(storageKeys.TOKEN);
  if (token) {
    removeItem(storageKeys.TOKEN);
    removeItem(storageKeys.USER);
  }
};

const validateToken = () => {
  let token = getItem(storageKeys.TOKEN);
  if (!token) {
    return { valid: false };
  }

  const valid = new Date(token.validUntil) >= new Date();
  if (!valid) {
    invalidate();
    token = null;
  }

  return { valid, token };
};

export { storageKeys, authenticate, invalidate, validateToken };
