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('system_experiences')
@Index('idx_system_experiences_tenant', ['tenantId'])
@Index('idx_system_experiences_type', ['experienceType'])
@Index('idx_system_experiences_status', ['verificationStatus'])
@Index('idx_system_experiences_active', ['isActive'])
export class SystemExperienceORM {
  @PrimaryColumn('uuid')
  id: string;

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

  @Column({ name: 'experience_type', type: 'varchar', length: 30 })
  experienceType: string;

  @Column('text')
  content: string;

  @Column({ type: 'int', default: 50 })
  confidence: number;

  @Column('text')
  scenario: string;

  @Column({ name: 'related_category', type: 'varchar', length: 50, nullable: true })
  relatedCategory?: string;

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

  @Column({ name: 'verification_status', type: 'varchar', length: 20, default: 'PENDING' })
  verificationStatus: string;

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

  @Column({ name: 'verified_at', type: 'timestamptz', nullable: true })
  verifiedAt?: Date;

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

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

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

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

  @Column({ name: 'is_active', type: 'boolean', default: false })
  isActive: boolean;

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

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