import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { DataModelEntity } from './data-model-entity.entity';

/**
 * Data Model Field Entity (schema: reports.data_model_fields)
 *
 * Represents columns/fields within a data model entity.
 * Includes metadata for filtering, sorting, grouping, and formatting.
 */
@Entity({ name: 'data_model_fields', schema: 'reports' })
@Index(['entityId', 'name'], { unique: true })
export class DataModelField {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'entity_id', type: 'uuid' })
  entityId: string;

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

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

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

  @Column({ name: 'data_type', type: 'varchar', length: 50 })
  dataType: string;

  @Column({ name: 'is_nullable', type: 'boolean', default: true })
  isNullable: boolean;

  @Column({ name: 'is_filterable', type: 'boolean', default: true })
  isFilterable: boolean;

  @Column({ name: 'is_sortable', type: 'boolean', default: true })
  isSortable: boolean;

  @Column({ name: 'is_groupable', type: 'boolean', default: false })
  isGroupable: boolean;

  @Column({ name: 'is_aggregatable', type: 'boolean', default: false })
  isAggregatable: boolean;

  @Column({ name: 'aggregation_functions', type: 'text', array: true, default: '{}' })
  aggregationFunctions: string[];

  @Column({ name: 'format_pattern', type: 'varchar', length: 100, nullable: true })
  formatPattern: string | null;

  @Column({ name: 'display_format', type: 'varchar', length: 50, nullable: true })
  displayFormat: string | 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;

  // Relations
  @ManyToOne(() => DataModelEntity, (entity) => entity.fields, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'entity_id' })
  entity: DataModelEntity;
}
