import { Entity, Column, Index, ManyToOne, JoinColumn } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { RoleEntity } from './role.entity';

/**
 * One row per role: which role it reports to.
 * `parent_role_id = null` means the role is a root of the tree.
 */
@Entity('role_hierarchy')
@Index('UQ_role_hierarchy_tenant_role', ['tenant_id', 'role_id'], {
  unique: true,
  where: '"is_deleted" = false',
})
@Index('ix_role_hierarchy_parent', ['tenant_id', 'parent_role_id'], {
  where: '"is_deleted" = false',
})
export class RoleHierarchyEntity extends BaseEntity {
  @Column({ type: 'uuid' })
  role_id: string;

  @Column({ type: 'uuid', nullable: true })
  parent_role_id: string | null;

  @ManyToOne(() => RoleEntity, { onDelete: 'RESTRICT' })
  @JoinColumn({ name: 'role_id' })
  role: RoleEntity;

  @ManyToOne(() => RoleEntity, { nullable: true, onDelete: 'RESTRICT' })
  @JoinColumn({ name: 'parent_role_id' })
  parent_role: RoleEntity | null;
}
