import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  OneToMany,
} from 'typeorm';
import { AccountType } from './account-type.entity.js';
import { Company } from '../../auth/entities/company.entity.js';

@Entity({ schema: 'financial', name: 'accounts' })
@Index('idx_accounts_tenant_id', ['tenantId'])
@Index('idx_accounts_company_id', ['companyId'])
@Index('idx_accounts_code', ['companyId', 'code'], { unique: true, where: 'deleted_at IS NULL' })
@Index('idx_accounts_parent_id', ['parentId'])
@Index('idx_accounts_account_type_id', ['accountTypeId'])
export class Account {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

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

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

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

  @Column({ type: 'boolean', default: false, nullable: false, name: 'is_reconcilable' })
  isReconcilable: boolean;

  @Column({ type: 'boolean', default: false, nullable: false, name: 'is_deprecated' })
  isDeprecated: boolean;

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

  // Relations
  @ManyToOne(() => Company)
  @JoinColumn({ name: 'company_id' })
  company: Company;

  @ManyToOne(() => AccountType)
  @JoinColumn({ name: 'account_type_id' })
  accountType: AccountType;

  @ManyToOne(() => Account, (account) => account.children)
  @JoinColumn({ name: 'parent_id' })
  parent: Account | null;

  @OneToMany(() => Account, (account) => account.parent)
  children: Account[];

  // Audit fields
  @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;
}
