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

/**
 * Widget type enum
 */
export enum WidgetType {
  KPI = 'kpi',
  BAR_CHART = 'bar_chart',
  LINE_CHART = 'line_chart',
  PIE_CHART = 'pie_chart',
  DONUT_CHART = 'donut_chart',
  GAUGE = 'gauge',
  TABLE = 'table',
  MAP = 'map',
  TEXT = 'text',
}

/**
 * Dashboard Widget Entity (schema: reports.dashboard_widgets)
 *
 * Individual visualization components within a dashboard.
 * Configures position, size, type, and data source.
 */
@Entity({ name: 'dashboard_widgets', schema: 'reports' })
export class DashboardWidget {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'dashboard_id', type: 'uuid' })
  dashboardId: string;

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

  @Index()
  @Column({
    name: 'widget_type',
    type: 'enum',
    enum: WidgetType,
    enumName: 'widget_type',
  })
  widgetType: WidgetType;

  @Column({ name: 'position_x', type: 'int', default: 0 })
  positionX: number;

  @Column({ name: 'position_y', type: 'int', default: 0 })
  positionY: number;

  @Column({ name: 'width', type: 'int', default: 3 })
  width: number;

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

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

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

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

  @Column({ name: 'sort_order', type: 'int', default: 0 })
  sortOrder: number;

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

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

  // Relations
  @ManyToOne(() => Dashboard, (dashboard) => dashboard.widgets, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'dashboard_id' })
  dashboard: Dashboard;

  @OneToMany(() => WidgetQuery, (query) => query.widget)
  queries: WidgetQuery[];
}
