/**
 * FondoGarantia Entity
 * Fondo de garantia acumulado por contrato
 *
 * @module Estimates
 * @table estimates.fondo_garantia
 * @ddl schemas/04-estimates-schema-ddl.sql
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { User } from '../../core/entities/user.entity';

@Entity({ schema: 'estimates', name: 'fondo_garantia' })
@Index(['contratoId'], { unique: true })
@Index(['tenantId'])
export class FondoGarantia {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'contrato_id', type: 'uuid' })
  contratoId: string;

  @Column({ name: 'accumulated_amount', type: 'decimal', precision: 16, scale: 2, default: 0 })
  accumulatedAmount: number;

  @Column({ name: 'released_amount', type: 'decimal', precision: 16, scale: 2, default: 0 })
  releasedAmount: number;

  // Columna calculada (GENERATED ALWAYS AS) - solo lectura
  @Column({
    name: 'pending_amount',
    type: 'decimal',
    precision: 16,
    scale: 2,
    insert: false,
    update: false,
  })
  pendingAmount: number;

  @Column({ name: 'release_date', type: 'date', nullable: true })
  releaseDate: Date | null;

  @Column({ name: 'released_at', type: 'timestamptz', nullable: true })
  releasedAt: Date | null;

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

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

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

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz', nullable: true })
  updatedAt: Date | null;

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

  @Column({ name: 'deleted_at', type: 'timestamptz', nullable: true })
  deletedAt: Date | null;

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

  // Relations
  @ManyToOne(() => Tenant)
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'released_by' })
  releasedBy: User | null;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'created_by' })
  createdBy: User | null;
}
