/**
 * Presupuesto Entity
 * Presupuestos de obra por prototipo o fraccionamiento
 *
 * @module Budgets
 * @table construction.presupuestos
 * @ddl schemas/01-construction-schema-ddl.sql
 */

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 { Fraccionamiento } from '../../construction/entities/fraccionamiento.entity';
import { PresupuestoPartida } from './presupuesto-partida.entity';

@Entity({ schema: 'construction', name: 'presupuestos' })
@Index(['tenantId', 'code', 'version'], { unique: true })
@Index(['tenantId'])
@Index(['fraccionamientoId'])
export class Presupuesto {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

  @Column({ type: 'varchar', length: 30 })
  code: string;

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

  @Column({ type: 'text', nullable: true })
  description: string | null;

  @Column({ type: 'integer', default: 1 })
  version: number;

  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive: boolean;

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

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

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

  @Column({ name: 'approved_by', type: 'uuid', nullable: true })
  approvedById: 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(() => Fraccionamiento, { nullable: true })
  @JoinColumn({ name: 'fraccionamiento_id' })
  fraccionamiento: Fraccionamiento | null;

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

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

  @OneToMany(() => PresupuestoPartida, (p) => p.presupuesto)
  partidas: PresupuestoPartida[];
}
