import { Check, Column, ManyToOne, OneToMany } from 'typeorm';
import { BaseEntity } from '../../base-entity';

export interface IMultiNamed {
  nameCanonical: string;
  multiNames: Promise<IMultiName[]>;
}

export interface IMultiName {
  name: string;
  multiNamed: Promise<IMultiNamed>;
}

export function MultiNamed<T extends Constructor>(BaseClass: T = null, multiNameClass: string): T {
  @Check(`LENGTH(nameCanonical) > 0`)
  class MixinClass extends BaseClass implements IMultiNamed {
    @Column()
    public nameCanonical: string;

    @OneToMany(multiNameClass, (multiName: IMultiName) => multiName.multiNamed)
    public multiNames: Promise<IMultiName[]>;
  }

  return MixinClass;
}

export function MultiName(multiNamedClass: string): Constructor {
  @Check(`LENGTH(name) > 0`)
  class MultiNameClass extends BaseEntity implements IMultiName {
    @Column()
    public name: string;

    @ManyToOne(multiNamedClass, (multiNamed: IMultiNamed) => multiNamed.multiNames, {
      nullable: false,
      onDelete: 'CASCADE',
      onUpdate: 'CASCADE',
    })
    public multiNamed: Promise<IMultiNamed>;
  }

  return MultiNameClass;
}
