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_tenant', ['tenantId'])
@Index('idx_knowledge_chunks_article', ['articleId'])
export class KnowledgeChunkORM {
  @PrimaryColumn('uuid')
  id: string;

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

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

  @Column('text')
  content: string;

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

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

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

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

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

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