import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  OneToMany,
} from 'typeorm';
import { DataModelField } from './data-model-field.entity';
import { DataModelRelationship } from './data-model-relationship.entity';

/**
 * Data Model Entity (schema: reports.data_model_entities)
 *
 * Represents database tables/entities available for report building.
 * Used by the report builder UI to construct dynamic queries.
 */
@Entity({ name: 'data_model_entities', schema: 'reports' })
@Index(['name'], { unique: true })
export class DataModelEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @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;

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

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

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

  @Column({ name: 'tenant_column', type: 'varchar', length: 100, nullable: true, default: 'tenant_id' })
  tenantColumn: string | null;

  @Column({ name: 'is_multi_tenant', type: 'boolean', default: true })
  isMultiTenant: boolean;

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

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

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

  // Relations
  @OneToMany(() => DataModelField, (field) => field.entity)
  fields: DataModelField[];

  @OneToMany(() => DataModelRelationship, (rel) => rel.sourceEntity)
  sourceRelationships: DataModelRelationship[];

  @OneToMany(() => DataModelRelationship, (rel) => rel.targetEntity)
  targetRelationships: DataModelRelationship[];
}
