import { RepositoryBase, IRepositoryBase } from '@tomei/general';
import FeedConfigModel from '../../models/price-feed-config.entity';
import { IFeedConfigAttr } from '../../interfaces/price-feed-config-attr.interface';
import { init } from '@paralleldrive/cuid2';

export class FeedConfigRepository
  extends RepositoryBase<FeedConfigModel>
  implements IRepositoryBase<FeedConfigModel>
{
  constructor() {
    super(FeedConfigModel);
  }

  async getConfig(dbTransaction?: any) {
    try {
      return await FeedConfigModel.findOne({
        order: [['UpdatedAt', 'DESC']],
        transaction: dbTransaction,
      });
    } catch (error) {
      throw new Error(`An Error occured when retriving : ${error.message}`);
    }
  }

  async updateConfig(config: IFeedConfigAttr, dbTransaction?: any) {
    try {
      const oldConfig = await this.getConfig(dbTransaction);
      if (oldConfig) {
        oldConfig.NotificationEmail = config.NotificationEmail;
        oldConfig.CutOffReminderInternal = config.CutOffReminderInternal;
        oldConfig.ManualPriceReminderInternal =
          config.ManualPriceReminderInternal;
        await oldConfig.save({
          transaction: dbTransaction,
        });
      }
    } catch (error) {
      throw new Error(`An Error occured when updating : ${error.message}`);
    }
  }

  async createConfig(config: IFeedConfigAttr, dbTransaction?: any) {
    try {
      const newConfig = new FeedConfigModel();
      newConfig.NotificationEmail = config.NotificationEmail;
      newConfig.CutOffReminderInternal = config.CutOffReminderInternal;
      newConfig.ManualPriceReminderInternal =
        config.ManualPriceReminderInternal;
      newConfig.UpdatedById = config.UpdatedById;
      newConfig.UpdatedAt = config.UpdatedAt;

      const generateId = init({
        length: 10,
      });
      newConfig.FeedConfigId = generateId().toUpperCase();
      return await newConfig.save({
        transaction: dbTransaction,
      });
    } catch (error) {
      throw new Error(`An Error occured when creating : ${error.message}`);
    }
  }
}
