/**
 * KpiValue Entity - Valores Calculados de KPIs
 *
 * Almacena los valores calculados periodicamente para cada KPI.
 *
 * @module Reports (MAI-006)
 * @table reports.kpis_values
 * @gap GAP-001
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { KpiConfig } from './kpi-config.entity';
import { TrendDirection } from './kpi-snapshot.entity';

export { TrendDirection };

export type PeriodType = 'daily' | 'weekly' | 'monthly' | 'quarterly' | 'yearly';

export type KpiStatus = 'green' | 'yellow' | 'red';

@Entity({ schema: 'reports', name: 'kpis_values' })
@Index(['tenantId'])
@Index(['kpiId'])
@Index(['tenantId', 'periodStart', 'periodEnd'])
@Index(['kpiId', 'periodStart'])
@Index(['tenantId', 'projectId'])
@Index(['calculatedAt'])
export class KpiValue {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // KPI
  @Column({ name: 'kpi_id', type: 'uuid' })
  kpiId!: string;

  // Periodo
  @Column({ name: 'period_start', type: 'date' })
  periodStart!: Date;

  @Column({ name: 'period_end', type: 'date' })
  periodEnd!: Date;

  @Column({
    name: 'period_type',
    type: 'varchar',
    length: 20,
    default: 'daily',
  })
  periodType!: PeriodType;

  // Contexto opcional
  @Column({ name: 'project_id', type: 'uuid', nullable: true })
  projectId?: string;

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

  // Valor calculado
  @Column({ type: 'decimal', precision: 18, scale: 4 })
  value!: number;

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

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

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

  @Column({ name: 'variance_percentage', type: 'decimal', precision: 8, scale: 2, nullable: true })
  variancePercentage?: number;

  // Semaforizacion calculada
  @Column({ type: 'varchar', length: 10, nullable: true })
  status?: KpiStatus;

  @Column({ name: 'is_on_target', type: 'boolean', nullable: true })
  isOnTarget?: boolean;

  // Tendencia
  @Column({ name: 'trend_direction', type: 'varchar', length: 10, nullable: true })
  trendDirection?: TrendDirection;

  @Column({ name: 'change_percentage', type: 'decimal', precision: 8, scale: 2, nullable: true })
  changePercentage?: number;

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

  // Calculo
  @Column({ name: 'calculated_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  calculatedAt!: Date;

  @Column({ name: 'calculation_duration_ms', type: 'int', nullable: true })
  calculationDurationMs?: number;

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

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

  @ManyToOne(() => KpiConfig, (config) => config.values)
  @JoinColumn({ name: 'kpi_id' })
  kpiConfig?: KpiConfig;

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