import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
  Unique,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';
import { Company } from './company.entity';
import { AuditRequest } from '../../audit-requests/entities/audit-request.entity';

@Entity('company_branches')
@Unique('uq_branch_company_norm', ['companyId', 'normalizedBranchName'])
@Unique('uq_branch_trade_license', ['tradeLicenseNo'])
@Unique('uq_one_head_office', ['companyId', 'isHeadOffice'])
@Index('idx_company_id')
@Index('idx_branch_name')
export class CompanyBranch {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'company_id', type: 'int' })
  companyId: number;

  @Column({ name: 'branch_name', type: 'varchar', length: 255 })
  branchName: string;

  @Column({ name: 'normalized_branch_name', type: 'varchar', length: 255 })
  normalizedBranchName: string;

  @Column({ name: 'trade_license_no', type: 'varchar', length: 100, nullable: true })
  tradeLicenseNo: string | null;

  @Column({ name: 'address', type: 'text', nullable: true })
  address: string | null;

  @Column({ name: 'city', type: 'varchar', length: 100, nullable: true })
  city: string | null;

  @Column({ name: 'country_id', type: 'int', nullable: true })
  countryId: number | null;

  @Column({ name: 'contact_person', type: 'varchar', length: 150, nullable: true })
  contactPerson: string | null;

  @Column({ name: 'designation', type: 'varchar', length: 255, nullable: true })
  designation: string | null;

  @Column({ name: 'email', type: 'varchar', length: 150, nullable: true })
  email: string | null;

  @Column({ name: 'mobile', type: 'varchar', length: 30, nullable: true })
  mobile: string | null;

  @Column({ name: 'telephone', type: 'varchar', length: 30, nullable: true })
  telephone: string | null;

  @Column({ name: 'scope_of_work', type: 'text', nullable: true })
  scopeOfWork: string | null;

  @Column({ name: 'certification_body', type: 'varchar', length: 100, nullable: true })
  certificationBody: string | null;

  @Column({ name: 'accreditation', type: 'varchar', length: 100, nullable: true })
  accreditation: string | null;

  @Column({ name: 'is_head_office', type: 'tinyint', default: 0 })
  isHeadOffice: number;

  @Column({ name: 'status', type: 'enum', enum: ['ACTIVE', 'INACTIVE'], default: 'ACTIVE' })
  status: string;

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

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

  // Relations
  @ManyToOne(() => Company, (c) => c.branches, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'company_id' })
  company: Company;

  @OneToMany(() => AuditRequest, (ar) => ar.branch)
  auditRequests: AuditRequest[];
}