import {CanActivateFn, Router} from '@angular/router';
import {inject} from '@angular/core';
import {IndexedDB} from '../storage/indexed-db';
import {Keyring} from '../storage/keyring';
import {KeyValue} from '../storage/key-value';
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';

export const authNeededGuard: CanActivateFn = (route, state) => {
  const indexedDb = inject(IndexedDB)
  const keyring = inject(Keyring)
  const keyValue = inject(KeyValue)
  const router = inject(Router)

  indexedDb.openDatabase().then(async () => {
    const sessionManager = new SessionManager(indexedDb.getApi(), keyring.getApi(), keyValue.getApi());
    const sessions = await sessionManager.loadSessions()

    if (sessions.length == 0) {
      router.navigate(['/signin'])
    }
  })

  return true;
};
