import { Service } from 'typedi';
import { FeatureFlagCode } from '../../../featureFlags/business/enums/featureFlagCode';
import { FeatureFlagService } from '../../../featureFlags/business/services/featureFlagService';
import { PermissionsService } from '../../../permissions/business/services/permissionsService';
import { UserInterface } from '../../../users/business/models/userInterface';
import { TIME_TRACKING_APP_GRANTS_DEFINITION, TimeTrackingAppGrant } from '../constants/timeTrackingGrants';

@Service()
export class TimeTrackingPermissions {
    constructor(
        private readonly featureFlagService: FeatureFlagService,
        private readonly permissionsService: PermissionsService,
    ) {}

    public getTargetGrants = async (actor: UserInterface, targetUserId: number): Promise<TimeTrackingAppGrant[]> => {
        if (!(await this.isCerberusEnabled(actor.getInstanceId()))) return [];
        return this.permissionsService.calculateGrantsForTarget(actor, targetUserId, TIME_TRACKING_APP_GRANTS_DEFINITION);
    };

    public getTargetsGrants = async (actor: UserInterface, targetUserIds: number[]): Promise<Map<number, TimeTrackingAppGrant[]>> => {
        if (!(await this.isCerberusEnabled(actor.getInstanceId()))) return new Map();
        return this.permissionsService.calculateGrantsForTargets(actor, targetUserIds, TIME_TRACKING_APP_GRANTS_DEFINITION);
    };

    private isCerberusEnabled = async (instanceId: number): Promise<boolean> => {
        const featureFlag = await this.featureFlagService.getBooleanFeatureFlag(FeatureFlagCode.TIME_TRACKING_CERBERUS_ENABLED, instanceId);
        return featureFlag.value;
    };
}
