/**
 * Retencion Entity
 * Retenciones aplicadas a estimaciones
 *
 * @module Estimates
 * @table estimates.retenciones
 * @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';
import { Estimacion } from './estimacion.entity';

export type RetentionType = 'guarantee' | 'tax' | 'penalty' | 'other';

@Entity({ schema: 'estimates', name: 'retenciones' })
@Index(['tenantId'])
@Index(['estimacionId'])
@Index(['retentionType'])
export class Retencion {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'estimacion_id', type: 'uuid' })
  estimacionId: string;

  @Column({
    name: 'retention_type',
    type: 'enum',
    enum: ['guarantee', 'tax', 'penalty', 'other'],
    enumName: 'estimates.retention_type',
  })
  retentionType: RetentionType;

  @Column({ type: 'varchar', length: 255 })
  description: string;

  @Column({ type: 'decimal', precision: 5, scale: 2, nullable: true })
  percentage: number | null;

  @Column({ type: 'decimal', precision: 16, scale: 2 })
  amount: 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_amount', type: 'decimal', precision: 16, scale: 2, nullable: true })
  releasedAmount: number | null;

  @Column({ type: 'text', nullable: true })
  notes: 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(() => Estimacion, (e) => e.retenciones)
  @JoinColumn({ name: 'estimacion_id' })
  estimacion: Estimacion;

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