import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToMany,
  JoinTable,
  ManyToOne,
  OneToMany,
  JoinColumn,
} from 'typeorm';
import { KnowledgeBase } from '../knowledge-base/knowledge-base.entity';
import { Tenant } from '../tenant/tenant.entity';

@Entity('knowledge_groups')
export class KnowledgeGroup {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  name: string;

  @Column({ nullable: true })
  description: string;

  @Column({ default: '#3B82F6' })
  color: string;

  // Removed userId field to make groups globally accessible
  // Tenant scoped: groups are shared within a tenant but isolated across tenants
  @Column({ name: 'tenant_id', nullable: true, type: 'text' })
  tenantId: string;

  @ManyToOne(() => Tenant, { nullable: true, onDelete: 'CASCADE' })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  // Hierarchical parent-child relationship
  @Column({ name: 'parent_id', nullable: true, type: 'text' })
  parentId: string | null;

  @ManyToOne(() => KnowledgeGroup, (group) => group.children, { nullable: true, onDelete: 'SET NULL' })
  @JoinColumn({ name: 'parent_id' })
  parent: KnowledgeGroup;

  @OneToMany(() => KnowledgeGroup, (group) => group.parent)
  children: KnowledgeGroup[];

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;

  @ManyToMany(() => KnowledgeBase, (kb) => kb.groups)
  @JoinTable({
    name: 'knowledge_base_groups',
    joinColumn: { name: 'group_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'knowledge_base_id', referencedColumnName: 'id' },
  })
  knowledgeBases: KnowledgeBase[];
}