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

/**
 * pgvector 类型转换器
 * 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('user_memories')
@Index('idx_user_memories_tenant', ['tenantId'])
@Index('idx_user_memories_user', ['userId'])
@Index('idx_user_memories_type', ['memoryType'])
export class UserMemoryORM {
  @PrimaryColumn('uuid')
  id: string;

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

  @Column({ name: 'user_id', type: 'uuid' })
  userId: string;

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

  @Column('text')
  content: string;

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

  @Column({ name: 'source_conversation_id', type: 'uuid', nullable: true })
  sourceConversationId?: string;

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

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

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

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

  @Column({ name: 'is_expired', type: 'boolean', default: false })
  isExpired: boolean;

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

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