/**
 * DepreciationEntry Entity - Entradas de Depreciacion
 *
 * Registro mensual de depreciacion aplicada por activo.
 *
 * @module Assets (MAE-015)
 * @table assets.depreciation_entries
 * @gap GAP-003
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
  Unique,
} from 'typeorm';
import { DepreciationSchedule } from './depreciation-schedule.entity';

export type DepreciationEntryStatus = 'draft' | 'posted' | 'reversed';

@Entity({ schema: 'assets', name: 'depreciation_entries' })
@Index(['tenantId'])
@Index(['scheduleId'])
@Index(['tenantId', 'periodDate'])
@Index(['tenantId', 'fiscalYear', 'fiscalMonth'])
@Index(['tenantId', 'status'])
@Unique(['scheduleId', 'periodDate'])
export class DepreciationEntry {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Programacion
  @Column({ name: 'schedule_id', type: 'uuid' })
  scheduleId!: string;

  @ManyToOne(() => DepreciationSchedule, (schedule) => schedule.entries)
  @JoinColumn({ name: 'schedule_id' })
  schedule?: DepreciationSchedule;

  // Periodo
  @Column({ name: 'period_date', type: 'date' })
  periodDate!: Date;

  @Column({ name: 'fiscal_year', type: 'int' })
  fiscalYear!: number;

  @Column({ name: 'fiscal_month', type: 'int' })
  fiscalMonth!: number;

  // Valores
  @Column({ name: 'depreciation_amount', type: 'decimal', precision: 12, scale: 2 })
  depreciationAmount!: number;

  @Column({ name: 'accumulated_depreciation', type: 'decimal', precision: 18, scale: 2 })
  accumulatedDepreciation!: number;

  @Column({ name: 'book_value', type: 'decimal', precision: 18, scale: 2 })
  bookValue!: number;

  // Para units_of_production
  @Column({ name: 'units_used', type: 'int', nullable: true })
  unitsUsed?: number;

  // Contabilidad
  @Column({ name: 'journal_entry_id', type: 'uuid', nullable: true })
  journalEntryId?: string;

  @Column({ name: 'is_posted', type: 'boolean', default: false })
  isPosted!: boolean;

  @Column({ name: 'posted_at', type: 'timestamptz', nullable: true })
  postedAt?: Date;

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

  // Estado
  @Column({
    type: 'varchar',
    length: 20,
    default: 'draft',
  })
  status!: DepreciationEntryStatus;

  // Notas
  @Column({ type: 'text', nullable: true })
  notes?: string;

  // Auditoria
  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdBy?: string;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt!: Date;
}
