import {
  Entity,
  Column,
  PrimaryColumn,
  CreateDateColumn,
  UpdateDateColumn,
  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_articles')
@Index('idx_knowledge_articles_category', ['category'])
@Index('idx_knowledge_articles_published', ['isPublished'])
export class KnowledgeArticleORM {
  @PrimaryColumn('uuid')
  id: string;

  @Column({ length: 500 })
  title: string;

  @Column('text')
  content: string;

  @Column('text', { nullable: true })
  summary: string;

  @Column({ length: 50 })
  category: string;

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

  @Column({ length: 20 })
  source: string;

  @Column({ name: 'source_url', length: 1000, nullable: true })
  sourceUrl?: string;

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

  @Column({ name: 'is_published', default: false })
  isPublished: boolean;

  @Column({ name: 'citation_count', default: 0 })
  citationCount: number;

  @Column({ name: 'helpful_count', default: 0 })
  helpfulCount: number;

  @Column({ name: 'unhelpful_count', default: 0 })
  unhelpfulCount: number;

  @Column({ name: 'quality_score', default: 50 })
  qualityScore: number;

  @Column({ name: 'created_by', nullable: true })
  createdBy?: string;

  @Column({ name: 'updated_by', nullable: true })
  updatedBy?: string;

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

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