import {
  BaseEntity,
  Column,
  Entity,
  EntityManager,
  PrimaryColumn,
} from 'typeorm';

@Entity()
export class Licensee extends BaseEntity {
  @PrimaryColumn({ type: 'int' })
  id: number;

  @Column({ default: null })
  email: string | null;

  /**
   * Returns DB record of a Licensee by given `licenseeId`
   * If there IS a DB record for given ID - will return this record,
   * if there IS NONE - will create a new one and return it.
   * @param licenseeId
   * @param manager Transaction (query runner) EntityManager.
   * Can be made optional for running outside of transactions
   */
  static async getById(
    licenseeId: number,
    manager: EntityManager
  ): Promise<Licensee> {
    let licensee = await Licensee.findOne(licenseeId);

    if (licensee === undefined) {
      licensee = new Licensee();
      licensee.id = licenseeId;
      // If running outside of transaction is needed - this part can be modified
      // so `manager` property is optional and if it's not received - use Licensee.save method
      await manager.save(licensee);
    }

    return licensee;
  }
}
