/**
 * HistoricoPuntos Entity
 * Histórico de puntos de crédito INFONAVIT
 *
 * @module Infonavit
 * @table infonavit.historico_puntos
 */

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

export type MovimientoTipo = 'initial' | 'update' | 'adjustment' | 'precalification';

@Entity({ schema: 'infonavit', name: 'historico_puntos' })
@Index(['tenantId', 'derechohabienteId', 'recordDate'])
export class HistoricoPuntos {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'derechohabiente_id', type: 'uuid' })
  derechohabienteId: string;

  @Column({ name: 'record_date', type: 'date' })
  recordDate: Date;

  @Column({ name: 'previous_points', type: 'integer' })
  previousPoints: number;

  @Column({ name: 'new_points', type: 'integer' })
  newPoints: number;

  @Column({ name: 'points_change', type: 'integer' })
  pointsChange: number;

  @Column({ name: 'movement_type', type: 'varchar', length: 20 })
  movementType: MovimientoTipo;

  @Column({ type: 'varchar', length: 255, nullable: true })
  source: string;

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

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

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

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

  @ManyToOne(() => Derechohabiente, (d) => d.historicoPuntos, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'derechohabiente_id' })
  derechohabiente: Derechohabiente;

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