import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  OneToMany,
} from 'typeorm';
import { Company } from '../../auth/entities/company.entity.js';
import { Journal } from './journal.entity.js';
import { JournalEntryLine } from './journal-entry-line.entity.js';

export enum EntryStatus {
  DRAFT = 'draft',
  POSTED = 'posted',
  CANCELLED = 'cancelled',
}

@Entity({ schema: 'financial', name: 'journal_entries' })
@Index('idx_journal_entries_tenant_id', ['tenantId'])
@Index('idx_journal_entries_company_id', ['companyId'])
@Index('idx_journal_entries_journal_id', ['journalId'])
@Index('idx_journal_entries_date', ['date'])
@Index('idx_journal_entries_status', ['status'])
export class JournalEntry {
  @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: 'uuid', nullable: false, name: 'journal_id' })
  journalId: string;

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

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

  @Column({ type: 'date', nullable: false })
  date: Date;

  @Column({
    type: 'enum',
    enum: EntryStatus,
    default: EntryStatus.DRAFT,
    nullable: false,
  })
  status: EntryStatus;

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

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

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

  @ManyToOne(() => Journal)
  @JoinColumn({ name: 'journal_id' })
  journal: Journal;

  @OneToMany(() => JournalEntryLine, (line) => line.entry, { cascade: true })
  lines: JournalEntryLine[];

  // 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: 'posted_at' })
  postedAt: Date | null;

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

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

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