import { notImplemented, unauthorized } from '@dvn/dvn-mock/api/utils';
import { STORAGE_KEY_KIMLIK_TOKEN, STORAGE_KEY_KIMLIK_USER_ID } from '@dvn/kimlik/api/kimlikApi';
import { UserSettings } from '@dvn/kimlik/api/models/UserSettings';
function findUserWithEmail(database, email) {
  const userId = Object.keys(database.kimlikUsers).find(id => database.kimlikUsers[id].email === email);
  return database.kimlikUsers[userId];
}
export class KimlikApiDemo {
  constructor(database, storage, logger) {
    this.logger = logger.new('KimlikApiDemo').setColor('emerald');
    this.storage = storage;
    this.database = database;
  }
  activateUser(email, firstName, lastName, password) {
    this.logger.debugGroup('activateUser', { email, firstName, lastName, password });
    const user = findUserWithEmail(this.database, email);
    user.status = 'active';
    user.firstName = firstName;
    user.lastName = lastName;
    // update user in database
    this.database.kimlikUsers[user._id] = user;
    this.storage.save(STORAGE_KEY_KIMLIK_USER_ID, user._id);
    this.storage.save(STORAGE_KEY_KIMLIK_TOKEN, `${user._id}-token`);
    return Promise.resolve({
      userId: user._id,
      jwt: `${user._id}-token`
    });
  }
  addAuthInterceptor(_token) {
    this.logger.debugGroup('addAuthInterceptor');
  }
  login(email, password) {
    if (password !== 'asdasd') {
      this.logger.errorGroup('login: password mismatch', { email, password });
      return Promise.reject(unauthorized());
    }
    const user = findUserWithEmail(this.database, email);
    if (user) {
      this.storage.save(STORAGE_KEY_KIMLIK_USER_ID, user._id);
      this.storage.save(STORAGE_KEY_KIMLIK_TOKEN, `${user._id}-token`);
      return Promise.resolve({
        userId: user._id,
        jwt: `${user._id}-token`
      });
    }
    this.logger.warnGroup('login: user not found', { email, password });
    return Promise.reject(unauthorized());
  }
  logout() {
    this.logger.debug('logout');
    this.storage.clear();
    return Promise.resolve({});
  }
  register(email, firstName, lastName, password) {
    this.logger.debugGroup('register', { email, firstName, lastName, password });
    return Promise.reject(notImplemented('register'));
  }
  getSession() {
    const token = this.storage.get(STORAGE_KEY_KIMLIK_TOKEN);
    this.logger.debugGroup('getSession', { token, storage: this.storage.getAll() });
    const userId = token.split('-')[0];
    const user = this.database.kimlikUsers[userId];
    if (user) {
      return Promise.resolve({ user, settings: UserSettings.decode({}) });
    }
    this.logger.errorGroup('getSession: user not found', { token, user });
    return Promise.reject(unauthorized());
  }
}
