import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  OneToMany,
} from 'typeorm';
import { Company } from '../../auth/entities/company.entity.js';
import { FiscalPeriod, FiscalPeriodStatus } from './fiscal-period.entity.js';

@Entity({ schema: 'financial', name: 'fiscal_years' })
@Index('idx_fiscal_years_tenant_id', ['tenantId'])
@Index('idx_fiscal_years_company_id', ['companyId'])
@Index('idx_fiscal_years_dates', ['dateFrom', 'dateTo'])
export class FiscalYear {
  @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: 100, nullable: false })
  name: string;

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

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

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

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

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

  @OneToMany(() => FiscalPeriod, (period) => period.fiscalYear)
  periods: FiscalPeriod[];

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

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