import Keycloak from 'keycloak-js';

const keycloak = new Keycloak({
  url: 'https://kc.bro-js.ru',
  realm: 'open',
  clientId: 'dry-wash',
});

const authLogin = async ({ redirect }) => {
  let user = null;

  try {
    const authenticated = await keycloak.init({ onLoad: 'login-required' });
    if (authenticated) {
      user = { ...(await keycloak.loadUserInfo()), ...keycloak.tokenParsed };

      const isOperator =
        user?.resource_access?.['dry-wash']?.roles.includes('operator');

      if (!isOperator) {
        redirect();
      }

      return user;
    } else {
      console.log('User is not authenticated');
    }
  } catch (error) {
    keycloak.login();
    console.error('Failed to initialize adapter:', error);
  }
};

export default authLogin;
