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

export interface ConversationMessage {
  role: 'user' | 'assistant';
  content: string;
  suggestions?: string[];
  timestamp: Date;
}

@Entity('ai_conversations')
@Index('idx_ai_conversations_user', ['userId'])
@Index('idx_ai_conversations_session', ['sessionId'], { unique: true })
export class AiConversation {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'jsonb', default: '[]' })
  messages: ConversationMessage[];

  @Column({ name: 'satisfaction_rating', type: 'smallint', nullable: true })
  satisfactionRating: number | null;

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

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

  // ── Domain Methods ──────────────────────────────────────────────────────────

  addUserMessage(content: string): void {
    this.messages.push({
      role: 'user',
      content,
      timestamp: new Date(),
    });
  }

  addAssistantMessage(content: string, suggestions?: string[]): void {
    this.messages.push({
      role: 'assistant',
      content,
      suggestions,
      timestamp: new Date(),
    });
  }

  rate(rating: number): void {
    if (rating < 1 || rating > 5) {
      throw new Error('Satisfaction rating must be between 1 and 5');
    }
    this.satisfactionRating = rating;
  }

  get messageCount(): number {
    return this.messages.length;
  }

  get lastMessageAt(): Date {
    return this.messages.length > 0
      ? this.messages[this.messages.length - 1].timestamp
      : this.createdAt;
  }
}
