import { ClassError, ObjectBase } from '@tomei/general';
import { RentalPriceRepository } from './rental-price.repository';
import { IRentalPriceAttr } from '../../interfaces/rental-price-attr.interface';
import { LoginUser } from '@tomei/sso';
import { ApplicationConfig } from '@tomei/config';

export class RentalPrice extends ObjectBase {
  ObjectId: string;
  ObjectName: string;
  ObjectType = 'RentalPrice';
  TableName: string;
  RetailPrice: number;
  Currency: string;
  PromoCode: string;
  Remarks: string;

  get PriceId() {
    return this.ObjectId;
  }

  set PriceId(value: string) {
    this.ObjectId = value;
  }

  private static _Repo = new RentalPriceRepository();

  private constructor(rentalPriceAttr?: IRentalPriceAttr) {
    super();
    if (rentalPriceAttr) {
      this.PriceId = rentalPriceAttr.PriceId;
      this.RetailPrice = rentalPriceAttr.RetailPrice;
      this.Currency = rentalPriceAttr.Currency;
      this.PromoCode = rentalPriceAttr.PromoCode;
      this.Remarks = rentalPriceAttr.Remarks;
    }
  }

  public static async init(dbTransaction?: any, priceId?: string) {
    try {
      if (priceId) {
        const rentalPrice = await RentalPrice._Repo.findByPk(
          priceId,
          dbTransaction,
        );
        if (rentalPrice) {
          return new RentalPrice(rentalPrice);
        } else {
          throw new ClassError(
            'RentalPrice',
            'RentalPriceErrMsg',
            'RentalPrice Not Found',
          );
        }
      }
      return new RentalPrice();
    } catch (error) {
      throw new ClassError(
        'RentalPrice',
        'RentalPriceErrMsg',
        'Failed To Initialize RentalPrice',
      );
    }
  }

  public async create(loginUser: LoginUser, dbTransaction?: any) {
    try {
      const systemCode =
        ApplicationConfig.getComponentConfigValue('system-code');
      const isPrivileged = await loginUser.checkPrivileges(
        systemCode,
        'Rental - Create',
      );

      if (!isPrivileged) {
        throw new ClassError(
          'RentalPrice',
          'RentalPriceErrMsg01',
          "You do not have 'Rental - Create' privilege.",
        );
      }

      this.PriceId = this.createId();

      await RentalPrice._Repo.create(
        {
          PriceId: this.PriceId,
          RetailPrice: this.RetailPrice,
          Currency: this.Currency,
          PromoCode: this.PromoCode,
          Remarks: this.Remarks,
        },
        dbTransaction,
      );

      return this;
    } catch (error) {
      throw error;
    }
  }
}
