import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { FiscalYear } from './fiscal-year.entity.js';

export enum FiscalPeriodStatus {
  OPEN = 'open',
  CLOSED = 'closed',
}

@Entity({ schema: 'financial', name: 'fiscal_periods' })
@Index('idx_fiscal_periods_tenant_id', ['tenantId'])
@Index('idx_fiscal_periods_fiscal_year_id', ['fiscalYearId'])
@Index('idx_fiscal_periods_dates', ['dateFrom', 'dateTo'])
@Index('idx_fiscal_periods_status', ['status'])
export class FiscalPeriod {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

  @Column({ type: 'varchar', length: 100, nullable: false })
  name: 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;

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

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

  // Relations
  @ManyToOne(() => FiscalYear, (year) => year.periods)
  @JoinColumn({ name: 'fiscal_year_id' })
  fiscalYear: FiscalYear;

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

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