import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  JoinColumn,
  ManyToMany,
  OneToMany,
  Index,
} from "typeorm"
import { BaseEntity } from "../../common/entities/base.entity"
import { Company } from "../../company/entities/company.entity"
import { MisBusinessKpis } from "src/modules/mis/entities/mis-business-kpis.entity"

@Index(["company_id", "name", "parent_id"], { unique: true })
@Entity("departments")
export class Department extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ type: "int", nullable: false })
  company_id: number

  @Column({ type: "varchar", length: 255, nullable: false })
  name: string

  @Column({ type: "text", nullable: true })
  description: string

  @Index()
  @Column({ type: "int", nullable: true })
  parent_id: number | null

  @Column({
    type: "smallint",
    default: 1,
  })
  status: number

  @ManyToOne(() => Company)
  @JoinColumn({ name: "company_id" })
  company: Company

  @ManyToMany(() => MisBusinessKpis, (kpi) => kpi.departments)
  businessKpis: MisBusinessKpis[]

  @ManyToOne(() => Department, (department) => department.subDepartment, {
    onDelete: "SET NULL",
  })
  @JoinColumn({ name: "parent_id" })
  parentDepartment: Department

  @OneToMany(() => Department, (department) => department.parentDepartment)
  subDepartment: Department[]
}
