import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { AIModel } from './model.entity';

@Entity({ name: 'embeddings', schema: 'ai' })
export class AIEmbedding {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;

  @Column({ name: 'content', type: 'text' })
  content: string;

  @Index()
  @Column({ name: 'content_hash', type: 'varchar', length: 64, nullable: true })
  contentHash: string;

  // Note: If pgvector is enabled, use 'vector' type instead of 'jsonb'
  @Column({ name: 'embedding_json', type: 'jsonb', nullable: true })
  embeddingJson: number[];

  @Column({ name: 'model_id', type: 'uuid', nullable: true })
  modelId: string;

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

  @Column({ name: 'dimensions', type: 'int', nullable: true })
  dimensions: number;

  @Index()
  @Column({ name: 'entity_type', type: 'varchar', length: 100, nullable: true })
  entityType: string;

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

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

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

  @Column({ name: 'chunk_index', type: 'int', nullable: true })
  chunkIndex: number;

  @Column({ name: 'chunk_total', type: 'int', nullable: true })
  chunkTotal: number;

  @Column({ name: 'parent_embedding_id', type: 'uuid', nullable: true })
  parentEmbeddingId: string;

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

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

  @ManyToOne(() => AIModel, { nullable: true })
  @JoinColumn({ name: 'model_id' })
  model: AIModel;

  @ManyToOne(() => AIEmbedding, { nullable: true })
  @JoinColumn({ name: 'parent_embedding_id' })
  parentEmbedding: AIEmbedding;
}
