import * as plugins from '../plugins.js';
import { UserManager } from './classes.usermanager.js';

/**
 * a User is identified by its username or email.
 * Both need to be unique and both can be changed.
 */
@plugins.smartdata.Manager()
export class User extends plugins.smartdata.SmartDataDbDoc<
  User,
  plugins.idpInterfaces.data.IUser
> {
  // STATIC
  public static async createNewUserForUserData(
    userDataArg: plugins.idpInterfaces.data.IUser['data']
  ): Promise<User> {
    const newUser = new User();
    newUser.id = plugins.smartunique.shortId();
    newUser.data = {
      connectedOrgs: null,
      status: 'new',
      name: userDataArg.name,
      username: userDataArg.username,
      email: userDataArg.email,
      passwordHash: userDataArg.passwordHash,
    };
    if (!newUser.data.passwordHash && userDataArg.password) {
      newUser.data.passwordHash = await User.hashPassword(userDataArg.password);
    }
    await newUser.save();
    return newUser;
  }

  public static hashPassword(passwordArg: string) {
    return plugins.smarthash.sha256FromString(passwordArg);
  }

  // INSTANCE
  @plugins.smartdata.unI()
  id: string;

  @plugins.smartdata.svDb()
  public data: plugins.idpInterfaces.data.IUser['data'];

  constructor() {
    super();
  }

  public setLegalData() {}
}
