/**
 * RegistroInfonavit Entity
 * Registro de proyectos ante INFONAVIT
 *
 * @module Infonavit
 * @table infonavit.registros_infonavit
 */

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

export type RegistroStatus = 'draft' | 'submitted' | 'approved' | 'active' | 'closed';

@Entity({ schema: 'infonavit', name: 'registros_infonavit' })
@Index(['tenantId', 'registrationNumber'], { unique: true })
export class RegistroInfonavit {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'fraccionamiento_id', type: 'uuid' })
  fraccionamientoId: string;

  @Column({ name: 'registration_number', type: 'varchar', length: 50 })
  registrationNumber: string;

  @Column({ name: 'registration_date', type: 'date' })
  registrationDate: Date;

  @Column({ name: 'approval_date', type: 'date', nullable: true })
  approvalDate: Date;

  @Column({ name: 'developer_code', type: 'varchar', length: 30, nullable: true })
  developerCode: string;

  @Column({ name: 'total_units', type: 'integer' })
  totalUnits: number;

  @Column({ name: 'registered_units', type: 'integer', default: 0 })
  registeredUnits: number;

  @Column({ name: 'assigned_units', type: 'integer', default: 0 })
  assignedUnits: number;

  @Column({ type: 'varchar', length: 20, default: 'draft' })
  status: RegistroStatus;

  @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;

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

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

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

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

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

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

  @OneToMany(() => OfertaVivienda, (oferta) => oferta.registro)
  ofertas: OfertaVivienda[];
}
