import {ClientNotificationType, SocketGateway} from '../socket/socket.gateway';
import { Injectable, Logger } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Config, ConfigDocument } from '../schemas/config.schema';
import { Model } from 'mongoose';
import {EventBus} from "@nestjs/cqrs";
@Injectable()
export class SharedService {
  private logger = new Logger(SharedService.name);
  constructor(
    private socketGateway: SocketGateway,
    @InjectModel(Config.name)
    private configModel: Model<ConfigDocument>,
  ) {
  }

  async getConfig(key: string) {
    const res =  await this.configModel
      .findOne({
        key,
      })
      .exec();
    if(!res) {
      return null;
    }
    return {
      key: res.key,
      value: res.value,
    }
  }

  async setConfig(key: string, value: string) {
    const cfgItem = await this.configModel
      .findOne({
        key,
      })
      .exec();
    if (!cfgItem) {
      const record = new this.configModel({
        key,
        value,
      });
      await record.save();
      return {
        key: record.key,
        value: record.value,
      }
    }
    cfgItem.value = value;
    await cfgItem.save();
    return {
      key: cfgItem.key,
      value: cfgItem.value,
    }
  }

  /**
   * Notifies all connected clients via the socket gateway with the given event and payload.
   *
   * @template T - The type of the payload.
   *
   * @param event - The event name to be sent to the clients.
   * @param payload - The data to be sent along with the event.
   *
   * @returns {void} - This function does not return any value.
   */
  notifyAllClients<T>(event: ClientNotificationType, payload: T): void {
    this.logger.verbose(`Sending notification to client: ${event}, ${JSON.stringify(payload)}`);
    this.socketGateway.notifyAllClients(event, payload);
  }


}
