/**
 * SupplierConstruction Entity
 * Extensión de proveedores para construcción
 *
 * @module Purchase (MAI-004)
 * @table purchase.supplier_construction
 * @ddl schemas/07-purchase-ext-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 { Partner } from '../../partners/entities/partner.entity';

@Entity({ schema: 'purchase', name: 'supplier_construction' })
@Index(['tenantId'])
@Index(['supplierId'], { unique: true })
@Index(['overallRating'])
export class SupplierConstruction {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  // FK a purchase.suppliers (ERP Core)
  @Column({ name: 'supplier_id', type: 'uuid' })
  supplierId: string;

  // Supplier type flags
  @Column({ name: 'is_materials_supplier', type: 'boolean', default: false })
  isMaterialsSupplier: boolean;

  @Column({ name: 'is_services_supplier', type: 'boolean', default: false })
  isServicesSupplier: boolean;

  @Column({ name: 'is_equipment_supplier', type: 'boolean', default: false })
  isEquipmentSupplier: boolean;

  @Column({ type: 'text', array: true, nullable: true })
  specialties: string[];

  // Ratings (1.00 - 5.00)
  @Column({ name: 'quality_rating', type: 'decimal', precision: 3, scale: 2, nullable: true })
  qualityRating: number;

  @Column({ name: 'delivery_rating', type: 'decimal', precision: 3, scale: 2, nullable: true })
  deliveryRating: number;

  @Column({ name: 'price_rating', type: 'decimal', precision: 3, scale: 2, nullable: true })
  priceRating: number;

  // Overall rating (computed in DB, but we can calculate in code too)
  @Column({
    name: 'overall_rating',
    type: 'decimal',
    precision: 3,
    scale: 2,
    nullable: true,
    insert: false,
    update: false,
  })
  overallRating: number;

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

  // Credit terms
  @Column({ name: 'credit_limit', type: 'decimal', precision: 14, scale: 2, nullable: true })
  creditLimit: number;

  @Column({ name: 'payment_days', type: 'int', default: 30 })
  paymentDays: number;

  // Documents status
  @Column({ name: 'has_valid_documents', type: 'boolean', default: false })
  hasValidDocuments: boolean;

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

  // Audit
  @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, { nullable: true })
  @JoinColumn({ name: 'created_by' })
  createdBy: User;

  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'updated_by' })
  updatedBy: User;

  // Computed property for overall rating
  calculateOverallRating(): number {
    const ratings = [this.qualityRating, this.deliveryRating, this.priceRating].filter(
      (r) => r !== null && r !== undefined
    );
    if (ratings.length === 0) return 0;
    return ratings.reduce((sum, r) => sum + Number(r), 0) / ratings.length;
  }

  // FK a partners.partners (ERP-Core) - el proveedor como partner
  @ManyToOne(() => Partner, { nullable: false })
  @JoinColumn({ name: 'supplier_id' })
  supplier: Partner;
}
