import {
  Column,
  Entity,
  JoinTable,
  ManyToMany,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { PolymorphicAuthor } from './core/polymorphic-author';
import { Permission } from './permission.entity';
import { Resource } from './resource.entity';
import { RoleAuthor } from './role-author.entity';
import { Timestamp } from './core/timestamp';

export enum AppRole {
  ROOT = 'root',
}

@Entity('roles')
export class Role extends Timestamp {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  role_name: string;

  @Column({ unique: true })
  role_key: string | AppRole;

  @Column('varchar', { array: true, default: [] })
  inherits: string[];

  @ManyToMany(() => Permission, (permission) => permission.roles, {
    cascade: true,
  })
  @JoinTable({
    name: 'role_permissions',
    joinColumn: { name: 'role_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'permission_id', referencedColumnName: 'id' },
  })
  permissions: Permission[];

  @ManyToMany(() => Resource, (resource) => resource.roles, { cascade: true })
  @JoinTable({
    name: 'role_resources',
    joinColumn: { name: 'role_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'resource_id', referencedColumnName: 'id' },
  })
  resources: Resource[];

  @OneToMany(() => RoleAuthor, (ra) => ra.role, { cascade: true })
  role_authors: RoleAuthor[];
}
