/**
 * OfertaVivienda Entity
 * Ofertas de vivienda registradas ante INFONAVIT
 *
 * @module Infonavit
 * @table infonavit.ofertas_vivienda
 */

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 { RegistroInfonavit } from './registro-infonavit.entity';
import { AsignacionVivienda } from './asignacion-vivienda.entity';

export type OfertaStatus = 'available' | 'reserved' | 'assigned' | 'delivered' | 'cancelled';

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

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

  @Column({ name: 'registro_id', type: 'uuid' })
  registroId: string;

  @Column({ name: 'lote_id', type: 'uuid' })
  loteId: string;

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

  @Column({ name: 'offer_date', type: 'date' })
  offerDate: Date;

  @Column({ name: 'sale_price', type: 'decimal', precision: 14, scale: 2 })
  salePrice: number;

  @Column({ name: 'infonavit_value', type: 'decimal', precision: 14, scale: 2 })
  infonavitValue: number;

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

  @Column({ name: 'construction_area', type: 'decimal', precision: 10, scale: 2 })
  constructionArea: number;

  @Column({ name: 'land_area', type: 'decimal', precision: 10, scale: 2 })
  landArea: number;

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

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

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

  @ManyToOne(() => RegistroInfonavit, (r) => r.ofertas, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'registro_id' })
  registro: RegistroInfonavit;

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

  @OneToMany(() => AsignacionVivienda, (a) => a.oferta)
  asignaciones: AsignacionVivienda[];
}
