import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { AIEmbedding } from './embedding.entity';

export type KnowledgeSourceType = 'manual' | 'document' | 'website' | 'api';
export type KnowledgeContentType = 'faq' | 'documentation' | 'policy' | 'procedure';

@Entity({ name: 'knowledge_base', schema: 'ai' })
@Unique(['tenantId', 'code'])
export class AIKnowledgeBase {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'code', type: 'varchar', length: 100 })
  code: string;

  @Column({ name: 'name', type: 'varchar', length: 200 })
  name: string;

  @Column({ name: 'description', type: 'text', nullable: true })
  description: string;

  @Column({ name: 'source_type', type: 'varchar', length: 30, nullable: true })
  sourceType: KnowledgeSourceType;

  @Column({ name: 'source_url', type: 'text', nullable: true })
  sourceUrl: string;

  @Column({ name: 'source_file_id', type: 'uuid', nullable: true })
  sourceFileId: string;

  @Column({ name: 'content', type: 'text' })
  content: string;

  @Column({ name: 'content_type', type: 'varchar', length: 50, nullable: true })
  contentType: KnowledgeContentType;

  @Index()
  @Column({ name: 'category', type: 'varchar', length: 100, nullable: true })
  category: string;

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

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

  @Column({ name: 'embedding_id', type: 'uuid', nullable: true })
  embeddingId: string;

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

  @Column({ name: 'relevance_score', type: 'decimal', precision: 5, scale: 4, nullable: true })
  relevanceScore: number;

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

  @Column({ name: 'is_verified', type: 'boolean', default: false })
  isVerified: boolean;

  @Column({ name: 'verified_by', type: 'uuid', nullable: true })
  verifiedBy: string;

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

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

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

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

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

  @ManyToOne(() => AIEmbedding, { nullable: true })
  @JoinColumn({ name: 'embedding_id' })
  embedding: AIEmbedding;
}
