import {Injectable, Logger} from '@nestjs/common';
import {SharedService} from "../shared/shared.service";
import {ClientNotificationType} from "../socket/socket.gateway";

export interface IFeatureFlagStatus {
  name: string;
  state: boolean;
}

@Injectable()
export class FeatureflagService {
  private logger = new Logger(FeatureflagService.name);
  constructor(private sharedService: SharedService ) {
  }

  async getFeatureFlag(id: string): Promise<IFeatureFlagStatus> {
    this.logger.verbose(`[getFeatureFlag] Getting feature flag status for ${id}`);
    const configRecord  = await this.sharedService.getConfig(`featureflag/${id}`);
    let ffState;
    if(!configRecord) {
      ffState = false;
    } else {
      ffState = configRecord.value !== 'false'
    }
    this.logger.verbose(`[getFeatureFlag] Feature flag status for ${id} is ${ffState}`);
    return {
      name: id,
      state: ffState
    }
  }

  async setFeatureFlag(id: string, status: boolean) : Promise<IFeatureFlagStatus> {
    this.logger.verbose(`Setting feature flag status for ${id} to ${status} `);
    const result = await this.sharedService.setConfig(`featureflag/${id}`, status.toString());
    const ffStatus: IFeatureFlagStatus = {
      name: id,
      state: result.value !== 'false',
    }
    this.sharedService.notifyAllClients<IFeatureFlagStatus>(ClientNotificationType.FeatureFlagChanged, ffStatus);
    return ffStatus;
  }

}
