import { inject, Injectable } from '@angular/core';
import { User } from '@red/domain';
import { QueryParam } from '@iqser/common-ui';
import { Roles } from '@users/roles';
import { of } from 'rxjs';
import { IIqserUser, IqserUserService } from '@iqser/common-ui/lib/users';
import { List } from '@iqser/common-ui/lib/utils';

@Injectable({
    providedIn: 'root',
})
export class UserService extends IqserUserService<IIqserUser, User> {
    protected readonly _defaultModelPath = 'user';
    protected readonly _entityClass = User;

    async loadCurrentUser(): Promise<User | undefined> {
        const currentUser = await super.loadCurrentUser();

        this._permissionsService.add({
            [Roles.any]: (permission, all) => Object.keys(all).some(key => this._permissionsFilter(key)),
        });

        return currentUser;
    }

    loadAll() {
        const canReadUsers = this._permissionsService.has(Roles.users.read);
        return canReadUsers ? super.loadAll() : of([]);
    }

    getAll() {
        const canReadAllUsers = this._permissionsService.has(Roles.users.readAll);
        const url = canReadAllUsers ? this._defaultModelPath : `${this._defaultModelPath}/red`;
        return super.getAll(url);
    }

    toggleStatus(user: User) {
        const queryParams: List<QueryParam> = [{ key: 'isActive', value: !user.active }];
        return this._post(null, `${this._defaultModelPath}/profile/activate/${user.userId}`, queryParams);
    }

    protected readonly _rolesFilter = (role: string) => role.startsWith('RED_');
    protected readonly _permissionsFilter = (role: string) => role.startsWith('red-') || role.startsWith('fforesight-');
}

export function getCurrentUser() {
    return inject(UserService).currentUser;
}
