import { buildTRestClients } from '@jig-software/trest-client';
import { atomWithStorage } from 'jotai/utils';
import { tokenContract } from './api';

export const authClient = buildTRestClients(
  {
    token: tokenContract,
  },
  (c) => c.baseUrl(`${location.origin}/auth/api`),
);

export const tokenAtom = atomWithStorage<string | undefined>(
  'token',
  undefined,
  undefined,
  {
    getOnInit: true,
  },
);

export const setToken = (token: string | null) => {
  if (token) {
    localStorage.setItem('token', token);
  } else {
    localStorage.removeItem('token');
  }
  return token;
};

export const getToken = (): string | null => {
  return localStorage.getItem('token');
};

export const isAuthenticated = (): boolean => {
  return !!getToken();
};
