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

/**
 * Relationship type enum
 */
export enum RelationshipType {
  ONE_TO_ONE = 'one_to_one',
  ONE_TO_MANY = 'one_to_many',
  MANY_TO_ONE = 'many_to_one',
  MANY_TO_MANY = 'many_to_many',
}

/**
 * Data Model Relationship Entity (schema: reports.data_model_relationships)
 *
 * Defines relationships between data model entities for join operations
 * in the report builder.
 */
@Entity({ name: 'data_model_relationships', schema: 'reports' })
@Index(['sourceEntityId', 'targetEntityId', 'name'], { unique: true })
export class DataModelRelationship {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'source_entity_id', type: 'uuid' })
  sourceEntityId: string;

  @Index()
  @Column({ name: 'target_entity_id', type: 'uuid' })
  targetEntityId: string;

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

  @Column({
    name: 'relationship_type',
    type: 'varchar',
    length: 20,
  })
  relationshipType: RelationshipType;

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

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

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

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

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

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

  @ManyToOne(() => DataModelEntity, (entity) => entity.targetRelationships, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'target_entity_id' })
  targetEntity: DataModelEntity;
}
