import { Organization } from './classes.organization.js';
import { Reception } from './classes.reception.js';
import { Role } from './classes.role.js';
import { User } from './classes.user.js';
import * as plugins from '../plugins.js';

export class RoleManager {
  // INSTANCE
  public receptionRef: Reception;
  public get db() {
    return this.receptionRef.db.smartdataDb;
  }
  public CRole = plugins.smartdata.setDefaultManagerForDoc(this, Role);
  constructor(receptionRefArg: Reception) {
    this.receptionRef = receptionRefArg;
  }

  public async modifyRoleForUserAtOrg(optionsArg: {
    action: 'create' | 'change' | 'delete';
    userId: string;
    organizationId: string;
    role: plugins.idpInterfaces.data.IRole['data']['role'];
  }) {
    let returnRole: Role;
    switch (optionsArg.action) {
      case 'create':
        returnRole = new this.CRole();
        returnRole.id = plugins.smartunique.shortId();
        returnRole.data = {
          userId: optionsArg.userId,
          organizationId: optionsArg.organizationId,
          role: optionsArg.role,
        };
        await returnRole.save();
    }
    return returnRole;
  }

  public async getRoleForUserAndOrg(userArg: User, orgArg: Organization) {
    const role = await this.CRole.getInstance({
      data: {
        userId: userArg.id,
        organizationId: orgArg.id,
      }
    })
    return role;
  }

  public async getAllRolesForUser(userArg: User) {
    const roles = await this.CRole.getInstances({
      data: {
        userId: userArg.id
      }
    });
    return roles;
  }
}
