import {
  Entity,
  Column,
  PrimaryColumn,
  CreateDateColumn,
  Index,
} from 'typeorm';

/**
 * pgvector 类型转换器
 */
const vectorTransformer = {
  to: (value: number[] | undefined): string | null => {
    if (!value || value.length === 0) return null;
    return `[${value.join(',')}]`;
  },
  from: (value: string | null): number[] | undefined => {
    if (!value) return undefined;
    const str = value.replace(/^\[|\]$/g, '');
    if (!str) return undefined;
    return str.split(',').map(Number);
  },
};

@Entity('knowledge_chunks')
@Index('idx_knowledge_chunks_article', ['articleId'])
export class KnowledgeChunkORM {
  @PrimaryColumn('uuid')
  id: string;

  @Column({ name: 'article_id' })
  articleId: string;

  @Column('text')
  content: string;

  @Column({ name: 'chunk_index' })
  chunkIndex: number;

  @Column({ name: 'chunk_type', length: 20 })
  chunkType: string;

  @Column({
    type: 'text',
    nullable: true,
    transformer: vectorTransformer,
  })
  embedding?: number[];

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

  @Column({ name: 'token_count', default: 0 })
  tokenCount: number;

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