/**
 * KpiConfig Entity - Configuracion de KPIs Dinamicos
 *
 * Permite definir KPIs con formulas configurables, umbrales
 * y semaforizacion.
 *
 * @module Reports (MAI-006)
 * @table reports.kpis_config
 * @gap GAP-001
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { KpiValue } from './kpi-value.entity';
import { KpiCategory } from './kpi-snapshot.entity';

export { KpiCategory };

export type FormulaType = 'sql' | 'expression' | 'function';

export type CalculationFrequency =
  | 'realtime'
  | 'hourly'
  | 'daily'
  | 'weekly'
  | 'monthly';

@Entity({ schema: 'reports', name: 'kpis_config' })
@Index(['tenantId', 'code'], { unique: true })
@Index(['tenantId'])
@Index(['tenantId', 'category'])
@Index(['tenantId', 'module'])
@Index(['tenantId', 'isActive'])
export class KpiConfig {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Identificacion
  @Column({ length: 50 })
  code!: string;

  @Column({ length: 200 })
  name!: string;

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

  // Clasificacion
  @Column({ length: 50 })
  category!: KpiCategory;

  @Column({ length: 50 })
  module!: string;

  // Formula de calculo
  @Column({ type: 'text' })
  formula!: string;

  @Column({
    name: 'formula_type',
    type: 'varchar',
    length: 20,
    default: 'sql',
  })
  formulaType!: FormulaType;

  @Column({ name: 'query_function', length: 255, nullable: true })
  queryFunction?: string;

  // Parametros de la formula
  @Column({ name: 'parameters_schema', type: 'jsonb', default: '{}' })
  parametersSchema!: Record<string, any>;

  // Unidad y formato
  @Column({ length: 20, nullable: true })
  unit?: string;

  @Column({ name: 'decimal_places', type: 'int', default: 2 })
  decimalPlaces!: number;

  @Column({ name: 'format_pattern', length: 50, nullable: true })
  formatPattern?: string;

  // Umbrales de semaforizacion
  @Column({ name: 'target_value', type: 'decimal', precision: 18, scale: 4, nullable: true })
  targetValue?: number;

  @Column({ name: 'threshold_green', type: 'decimal', precision: 18, scale: 4, nullable: true })
  thresholdGreen?: number;

  @Column({ name: 'threshold_yellow', type: 'decimal', precision: 18, scale: 4, nullable: true })
  thresholdYellow?: number;

  @Column({ name: 'invert_colors', type: 'boolean', default: false })
  invertColors!: boolean;

  // Frecuencia de calculo
  @Column({
    name: 'calculation_frequency',
    type: 'varchar',
    length: 20,
    default: 'daily',
  })
  calculationFrequency!: CalculationFrequency;

  // Visualizacion
  @Column({ name: 'display_order', type: 'int', default: 0 })
  displayOrder!: number;

  @Column({ length: 50, nullable: true })
  icon?: string;

  @Column({ length: 20, nullable: true })
  color?: string;

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

  @Column({ name: 'is_system', type: 'boolean', default: false })
  isSystem!: boolean;

  // Metadatos
  @Column({ type: 'jsonb', nullable: true })
  metadata?: Record<string, any>;

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

  @OneToMany(() => KpiValue, (value) => value.kpiConfig)
  values?: KpiValue[];

  // Auditoria
  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdBy?: string;

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

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

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

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