import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  ManyToMany,
} from 'typeorm';
import { Tenant } from './tenant.entity.js';
import { User } from './user.entity.js';

@Entity({ schema: 'auth', name: 'companies' })
@Index('idx_companies_tenant_id', ['tenantId'])
@Index('idx_companies_parent_company_id', ['parentCompanyId'])
@Index('idx_companies_active', ['tenantId'], { where: 'deleted_at IS NULL' })
@Index('idx_companies_tax_id', ['taxId'])
export class Company {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'tenant_id' })
  tenantId: string;

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

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

  @Column({ type: 'varchar', length: 50, nullable: true, name: 'tax_id' })
  taxId: string | null;

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

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

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

  @Column({ type: 'jsonb', default: {} })
  settings: Record<string, any>;

  // Relaciones
  @ManyToOne(() => Tenant, (tenant) => tenant.companies, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  @ManyToOne(() => Company, (company) => company.childCompanies, {
    nullable: true,
  })
  @JoinColumn({ name: 'parent_company_id' })
  parentCompany: Company | null;

  @ManyToMany(() => Company)
  childCompanies: Company[];

  @ManyToMany(() => User, (user) => user.companies)
  users: User[];

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

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

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

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

  @Column({ type: 'timestamp', nullable: true, name: 'deleted_at' })
  deletedAt: Date | null;

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