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

export enum JournalType {
  SALE = 'sale',
  PURCHASE = 'purchase',
  CASH = 'cash',
  BANK = 'bank',
  GENERAL = 'general',
}

@Entity({ schema: 'financial', name: 'journals' })
@Index('idx_journals_tenant_id', ['tenantId'])
@Index('idx_journals_company_id', ['companyId'])
@Index('idx_journals_code', ['companyId', 'code'], { unique: true, where: 'deleted_at IS NULL' })
@Index('idx_journals_type', ['journalType'])
export class Journal {
  @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: 255, nullable: false })
  name: string;

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

  @Column({
    type: 'enum',
    enum: JournalType,
    nullable: false,
    name: 'journal_type',
  })
  journalType: JournalType;

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

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

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

  @Column({ type: 'boolean', default: true, nullable: false })
  active: boolean;

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

  @ManyToOne(() => Account)
  @JoinColumn({ name: 'default_account_id' })
  defaultAccount: Account | null;

  // 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;
}
