import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { DashboardWidget } from './dashboard-widget.entity';

/**
 * Widget Query Entity (schema: reports.widget_queries)
 *
 * Data source queries for dashboard widgets.
 * Supports both raw SQL and function-based queries with caching.
 */
@Entity({ name: 'widget_queries', schema: 'reports' })
export class WidgetQuery {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'widget_id', type: 'uuid' })
  widgetId: string;

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

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

  @Column({ name: 'query_function', type: 'varchar', length: 255, nullable: true })
  queryFunction: string | null;

  @Column({ name: 'parameters', type: 'jsonb', default: '{}' })
  parameters: Record<string, any>;

  @Column({ name: 'result_mapping', type: 'jsonb', default: '{}' })
  resultMapping: Record<string, any>;

  @Column({ name: 'cache_ttl_seconds', type: 'int', nullable: true, default: 300 })
  cacheTtlSeconds: number | null;

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

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

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

  // Relations
  @ManyToOne(() => DashboardWidget, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'widget_id' })
  widget: DashboardWidget;
}
