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_tenant', ['tenantId'])
@Index('idx_knowledge_articles_category', ['category'])
@Index('idx_knowledge_articles_published', ['isPublished'])
export class KnowledgeArticleORM {
  @PrimaryColumn('uuid')
  id: string;

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

  @Column({ type: 'varchar', length: 500 })
  title: string;

  @Column('text')
  content: string;

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

  @Column({ type: 'varchar', length: 50 })
  category: string;

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

  @Column({ type: 'varchar', length: 20 })
  source: string;

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

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

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

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

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

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

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

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

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

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

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